C++ Classes & Objects

C++ supports classes with public/private/protected access, constructors, destructors, and inheritance. Classes are the foundation of object-oriented programming in C++.

Basic Class

CPP
#include <iostream>
#include <string>
using namespace std;

class Book {
private:     // only accessible inside the class
    string title;
    int pages;

public:      // accessible from anywhere
    // Constructor — called when creating an object
    Book(string t, int p) : title(t), pages(p) {}

    // Methods
    string getTitle() const { return title; }
    int getPages() const { return pages; }

    void describe() const {
        cout << title << " (" << pages << " pages)" << endl;
    }
};

int main() {
    Book book("Palpasa Cafe", 312);
    book.describe(); // "Palpasa Cafe (312 pages)"
}

Constructor Initialiser List

Always prefer the initializer list over assignment in the constructor body — it is more efficient:

CPP
class Point {
public:
    int x, y;

    // ✅ Good — initializer list
    Point(int x, int y) : x(x), y(y) {}

    // ❌ Avoid — assignment (default-constructs first, then assigns)
    // Point(int x, int y) { this->x = x; this->y = y; }
};

Access Modifiers

Modifier Inside Class Subclass Outside
public ✅ ✅ ✅
protected ✅ ✅ ❌
private ✅ ❌ ❌

Default in class is private; in struct it is public.

Inheritance

CPP
class Animal {
public:
    void speak() { cout << "..." << endl; }
};

class Dog : public Animal {
public:
    void speak() override { cout << "Woof!" << endl; }
};

int main() {
    Dog rex;
    rex.speak(); // "Woof!"
}

Destructors

Called automatically when an object goes out of scope — use for cleanup:

CPP
class Resource {
public:
    Resource()  { cout << "Acquired" << endl; }
    ~Resource() { cout << "Released" << endl; }  // destructor
};

{
    Resource r;  // prints "Acquired"
}  // prints "Released" — r goes out of scope

Struct vs Class

In C++, struct and class are identical except that struct members are public by default.

CPP
struct Point {   // public by default
    int x, y;
};

class Circle {   // private by default
    double radius;
public:
    Circle(double r) : radius(r) {}
};

Rule of thumb: use struct for plain data holders, class for objects with behaviour.

Tips

  • Use initializer lists — they are more efficient and required for const members.
  • Mark methods const when they do not modify the object — it enables calling them on const objects.
  • Keep classes small — if a class has more than ~10 methods, it might be doing too much.
  • Use struct for simple data, class for complex objects.

Next: STL — vectors, maps, and algorithms.