C++ Classes and Objects
Bundle data and behavior together: define classes, construct objects, and use access specifiers, constructors, and methods.
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.
#include <iostream>
#include <string>
class Player {
public:
std::string name;
int level = 1;
void greet() const {
std::cout << "Hello, I am " << name << " (level " << level << ").\n";
}
};
int main() {
Player p; // object
p.name = "Ada";
p.level = 5;
p.greet(); // Hello, I am Ada (level 5).
}cppAccess 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; }
};cppOutside 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) {}
};cppThe member initializer list : name(n), level(l) sets the members. Objects now need arguments:
Player p("Ada", 5);cppMethods#
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; }cppEncapsulation in practice#
class BankAccount {
private:
double balance = 0;
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
double getBalance() const { return balance; }
};cppThe 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.