Access Specifiers
Access specifiers define the scope and visibility of class members:
- private: Accessible only within the same class.
- protected: Accessible in the class and its derived classes.
- public: Accessible from anywhere the object is visible.
Example:
class Test {
private:
int a;
protected:
int b;
public:
int c;
};
10.5 Static Members
Static members are shared among all objects of a class. They are declared with the static keyword.
Example:
class Counter {
public:
static int count;
Counter() { count++; }
};
int Counter::count = 0;
This Pointer
This is a special pointer that holds the address of the current object. It’s used to distinguish between local and class variables with the same name.
Example:
class Test {
int x;
public:
void setX(int x) { this->x = x; }
};
10.7 Dynamic Memory Allocation with Classes
Dynamic allocation allows creation of objects at runtime using new and destruction using delete.
Example:
class Box {
public:
void show() { cout << “Box created” << endl; }
};
int main() {
Box* b = new Box();
b->show();
delete b;
return 0;
}
10.8 Friend Functions and Classes
Friend functions can access private and protected members of a class. A friend class can access another class’s private members.
Example:
class A {
int x = 10;
friend void show(A);
};
void show(A a) {
cout << a.x << endl;
}