length/width in the Rectangle example below — every Rectangle object has its own values)static, shared across all objects of the class — one copy total, not one per object (see the Classes Advanced page for full static coverage)Rectangle(double l, double w) : length(l), width(w) {}) over assigning inside the constructor body — it's more efficient and required for const/reference members| Type | Purpose | Example |
|---|---|---|
| Accessor ("getter") | Reads a data member's value without modifying it | double getBalance() const { return balance; } |
| Mutator ("setter") | Modifies a data member's value in a controlled way | void deposit(double amt) { balance += amt; } |
| Utility/helper | Performs a computation using the object's data | double area() { return length * width; } |
| Constructor/Destructor | Special member functions for initialization/cleanup | see the Rectangle example below |
inline (compiler may substitute the call with the function body directly, avoiding call overhead — relevant for short, frequently-called functions)const (like getBalance() const above) to guarantee they don't modify the object — lets them be called on const objects too| 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.
#include <iostream>
using namespace std;
class Rectangle
{
private:
double length, width; // data members -- hidden from outside access
public:
Rectangle(double l, double w) : length(l), width(w) // constructor
{
cout << "Rectangle created.\n";
}
double area() { return length * width; } // member function
double perimeter() { return 2 * (length + width); }
~Rectangle() // destructor
{
cout << "Rectangle destroyed.\n";
}
};
int main()
{
Rectangle r(5, 3);
cout << "Area: " << r.area() << endl;
cout << "Perimeter: " << r.perimeter() << endl;
return 0; // destructor runs automatically here
}
Output:
Rectangle created.
Area: 15
Perimeter: 16
Rectangle destroyed.
ClassName(const ClassName& other) — builds a new object as a copy of an existing one; the compiler auto-generates a shallow-copy version unless you define your own)