| Specifier | Accessible from |
|---|---|
private |
Only within the same class (default for class) |
protected |
Same class + any derived class, not from outside |
public |
Anywhere the object is visible |
Note: struct defaults to public access; class defaults to private — a classic MCQ trap.
class Rectangle
{
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() { return length * width; }
};
int main()
{
Rectangle r(5, 3); // r is an OBJECT -- an instance of the Rectangle CLASS
cout << r.area(); // 15
}
A class is a template; it occupies no memory for data on its own (memory is only reserved when an object is created). An object is a real instance built from that template, occupying its own dedicated memory.
class Rectangle // BLUEPRINT -- defines what a rectangle looks like, no memory for actual data yet
{
private:
double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() { return length * width; }
};
int main()
{
Rectangle r1(5, 3); // OBJECT #1 -- its own length/width in memory
Rectangle r2(10, 2); // OBJECT #2 -- separate length/width, doesn't affect r1
cout << r1.area(); // 15
cout << r2.area(); // 20 -- independent of r1
}
Each object gets its own copy of instance data members but shares the same member function code (there's only one area() function in memory, used by every object).
When Rectangle r1(5, 3); runs:
r1's length and widthr1.area() reads r1's own length/width — not some shared or global valueclass (not struct) is:
struct in C++ defaults its members to:
Rectangle r1(5,3) and Rectangle r2(10,2) are both created, changing r1's data: