Tutorials › C++ › Objects
Intermediate 7 min read Lesson 23 of 50
Creating Objects
An object is an instance of a class. You can create many objects from the same class.
#include <iostream>
using namespace std;
class Rectangle {
public:
double width;
double height;
double area() { return width * height; }
double perimeter() { return 2 * (width + height); }
};
int main() {
Rectangle r1, r2;
r1.width = 5.0; r1.height = 3.0;
r2.width = 8.5; r2.height = 4.2;
cout << "R1 Area: " << r1.area() << endl;
cout << "R1 Perimeter: " << r1.perimeter() << endl;
cout << "R2 Area: " << r2.area() << endl;
return 0;
}
Output:
R1 Area: 15
R1 Perimeter: 16
R2 Area: 35.7
The this Pointer
Inside a method, this is a pointer to the current object:
class Box {
public:
int size;
void setSize(int size) {
this->size = size; // 'this->size' is the member; 'size' is the parameter
}
};
Exercise
Create a BankAccount class with owner (string), balance (double). Add methods deposit(double), withdraw(double), and printBalance(). Test with two accounts.
Show Solution
#include <iostream>
using namespace std;
class BankAccount {
public:
string owner;
double balance;
void deposit(double amount) { balance += amount; }
void withdraw(double amount) { if (amount <= balance) balance -= amount; }
void printBalance() { cout << owner << ": $" << balance << endl; }
};
int main() {
BankAccount acc;
acc.owner = "Alice"; acc.balance = 1000.0;
acc.deposit(500);
acc.withdraw(200);
acc.printBalance(); // Alice: $1300
return 0;
}
Quiz
What is the relationship between a class and an object?
A) They are the same thing B) A class is an instance of an object C) An object is an instance of a class D) Objects contain classes Answer C) A class is the blueprint; an object is a concrete instance of that blueprint.
Summary
Objects are instances of classes created using the class name as a type.
Each object has its own copy of member variables.
this is a pointer to the current object inside a method.