1. Class fundamentals
- Class = data + member functions; default
private(struct defaults topublic). - Access specifiers:
public,protected,private. - Constructors initialize; destructors clean up.
class Counter {
public:
Counter(int n = 0) : value_(n) {} // member initializer list
~Counter() = default;
private:
int value_;
};
- Initializer list is preferred over assignment in body — members initialized, not default-constructed-then-assigned.
2. Rule of three / five
If a class manages a resource (raw pointer), define all of:
- copy constructor
- copy assignment operator
- destructor
And in modern C++ also: 4. move constructor 5. move assignment operator
= defaultand= deleteto control implicit ones.- If you write a destructor, copy/move get implicitly deleted — declare what you need explicitly.
class Buffer {
public:
Buffer(size_t n) : size_(n), data_(new char[n]) {}
~Buffer() { delete[] data_; }
// copy ctor, copy assignment, move ctor, move assignment...
private:
size_t size_;
char* data_;
};
3. Inheritance basics
class Derived : public Base— public inheritance means “is-a”.- Access:
- public base → public stays public
- protected base → public becomes protected
- private base → all become private
- Constructors: derived must init base; base default ctor runs implicitly or in init list.
- Destructors: derived first, then base. Base destructor must be virtual when deleting through a base pointer.
4. Virtual functions & the vtable
virtualfunctions enable runtime polymorphism; dispatch via a vtable pointer.virtual+ override; a slot in a table per class; each object holds avptr.overridekeyword makes redefinitions explicit (and compiler-checked).- constructors are never virtual; destructors are often virtual.
class Shape {
public:
virtual ~Shape() = default;
virtual int area() const { return 0; }
};
class Rect : public Shape {
public:
int area() const override { return w_ * h_; }
};
finalprevents further overriding;overridecatches mistakes.- Virtual dispatch is not decided at compile time — depends on dynamic type.
5. Abstract classes & pure virtual
virtual int fn() = 0;→ pure virtual; class is abstract, can’t instantiate.- Concrete subclass must implement pure functions to be instantiable.
- Interfaces (all abstract) still allowed via pure virtual functions.
6. Interview checkpoint
- Rule of five vs rule of three; when
= default. - Virtual destructor necessity (delete via base pointer).
- Pure virtual → abstract class; why can’t you instantiate it.
overrideprevents silent bugs.- Private/protected inheritance caveats.
Premium Content
Unlock Part 2: Classes, OOP & Virtual and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans