blog.dopana

Back

Final post in the basic C++ series. Classes bundle data and the functions that operate on it into a single unit — the heart of object-oriented programming.

What is a class?#

A class is a blueprint. An object is a concrete instance created from that blueprint.

Access specifiers#

  • public: — accessible from anywhere.
  • private: — accessible only inside the class.

Data is usually private, with public member functions as the interface. This is encapsulation.

class Counter {
private:
    int count = 0;

public:
    void increment() { ++count; }
    int get() const { return count; }
};
cpp

Outside code cannot touch count directly — it must go through increment() and get().

Constructors#

A constructor runs when an object is created. It has the same name as the class and no return type:

class Player {
public:
    std::string name;
    int level;

    Player(std::string n, int l) : name(n), level(l) {}
};
cpp

The member initializer list : name(n), level(l) sets the members. Objects now need arguments:

Player p("Ada", 5);
cpp

Methods#

Member functions declared inside the class operate on that object. The trailing const promises the method will not modify the object:

int getLevel() const { return level; }
cpp

Encapsulation in practice#

class BankAccount {
private:
    double balance = 0;

public:
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    double getBalance() const { return balance; }
};
cpp

The balance cannot be set to a negative value from outside — the class controls its own data.

Conclusion#

That wraps up the basic C++ series: first program, variables and types, control flow, functions, pointers and references, and now classes. Build small programs with each concept and keep going — the standard library and STL are the natural next step.

References#