Classes and Objects
Classes and Objects
A class groups related data (member variables) and behavior (member functions) into a single unit. An object is an instance of a class.
Defining a Class
class Rectangle {
public:
int width;
int height;
int area() {
return width * height;
}
int perimeter() {
return 2 * (width + height);
}
};
class— the keyword (vs C'sstruct)public:— these members are accessible from outside the classint area()— a member function that can accesswidthandheightdirectly
Creating Objects
Rectangle r; // create an object
r.width = 10; // set member variables
r.height = 5;
cout << r.area(); // call a member function → 50
Multiple Objects
Each object has its own copy of the member variables:
Rectangle a, b;
a.width = 3; a.height = 4;
b.width = 6; b.height = 2;
cout << a.area() << endl; // 12
cout << b.area() << endl; // 12
The this Pointer
Inside a member function, this is a pointer to the current object. You can write this->width to explicitly access a member, but it's optional — writing width alone works the same way. The this-> prefix is mainly useful when a parameter name shadows a member variable (e.g., this->width = width; in a constructor).
Member Functions Have Access to Members
Inside a member function, you can access any member variable or function of the same class:
class Circle {
public:
double radius;
double area() {
return 3.14159 * radius * radius;
}
bool isLargerThan(Circle other) {
return radius > other.radius;
}
};
Class vs struct
In C++, class and struct are nearly identical. The only difference:
structmembers arepublicby defaultclassmembers areprivateby default
Your Task
Define a Rectangle class with width and height (both int), plus area() and perimeter() methods. Create a rectangle with width 4 and height 3 and print its area and perimeter.