optional · CSS study notes
Classes Advanced (extended)
friend: a function or class granted access to another class's private/protected members despite not being a member itself — breaks strict encapsulation deliberately for specific, controlled casesstaticmember: shared across all objects of a class (one copy total), rather than per-object — accessed via the class name, not requiring an instance- Composition ("has-a" relationship): a class contains an object of another class as a member, as opposed to inheritance's "is-a" relationship
thispointer: an implicit pointer available inside non-static member functions, pointing to the calling object itselfconst: qualifier preventing modification —constmember functions cannot modify the object's data members;constparameters/objects cannot be altered- Static member function: declared with
static, callable without any object (ClassName::function()); it has nothispointer, so it can only directly access otherstaticmembers
C++ Examples
friend function — external function granted access to private members:
class Box
{
private:
double width;
public:
Box(double w) : width(w) {}
friend void printWidth(Box b); // declared inside, defined outside
};
void printWidth(Box b) { cout << b.width; } // can read private 'width'
static data member + static member function — one copy shared by all objects:
class Counter
{
private:
static int count; // ONE copy for the whole class
public:
Counter() { count++; }
static int getCount() { return count; } // no object needed to call this
};
int Counter::count = 0; // static data members must be defined outside the class
// Counter::getCount(); -- called via class name, not an object
Composition ("has-a") — a class contains another class as a member:
class Engine
{
public:
void start() { cout << "Engine started\n"; }
};
class Car
{
private:
Engine engine; // Car "has-a" Engine
public:
void start() { engine.start(); } // delegates to the contained object
};
this pointer — implicit pointer to the calling object:
class Point
{
private:
int x;
public:
Point(int x) { this->x = x; } // disambiguates param vs member
Point& setX(int x) { this->x = x; return *this; } // enables obj.setX(1).setX(2) chaining
};
const member function — promises not to modify the object:
class Circle
{
private:
double radius;
public:
Circle(double r) : radius(r) {}
double getRadius() const { return radius; } // callable on a const Circle too
};
MCQ Trap
staticmembers belong to the class (one shared copy); non-static (instance) members belong to each object separately.- A
constmember function cannot call a non-constmember function on the same object — the compiler blocks it since that could indirectly modify state friendis not mutual and not inherited: ifAdeclaresBas a friend,Bdoes NOT automatically get to treatAas a friend, and a class derived fromBdoes not inherit the friendship either