C++ Classes and Objects
C++ classes and objects are the heart of object-oriented programming. A class is a blueprint that bundles data (members) with the functions that operate on it, and an object is an instance created from that blueprint.
Creating a Class
#include <iostream>
#include <string>
class Car {
public:
std::string brand;
int year;
void describe() const {
std::cout << brand << " (" << year << ")\n";
}
};
int main() {
Car a;
a.brand = "Toyota";
a.year = 2022;
a.describe();
}Toyota (2022)
Access Specifiers and Encapsulation
private members can only be used inside the class. Public member functions control how the outside world reads and changes the data, protecting the object from invalid states.
#include <iostream>
class BankAccount {
private:
double balance = 0;
public:
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() const { return balance; }
};
int main() {
BankAccount acc;
acc.deposit(200);
std::cout << std::boolalpha << acc.withdraw(500) << '\n';
acc.withdraw(50);
std::cout << acc.getBalance() << '\n';
}false 150
Access Specifiers
- public: accessible from anywhere
- private: accessible only inside the class (default for class)
- protected: accessible in the class and its derived classes
- A struct is the same as a class except members are public by default.
const Member Functions
Adding const after a member function promises it will not modify the object. Such functions can be called on const objects, so mark every read-only method const.
Frequently asked questions
What is the difference between a class and an object in C++?
A class is the definition or blueprint. An object is a concrete instance of that class in memory with its own values.
What is the difference between struct and class in C++?
The only language difference is default access: struct members are public by default and class members are private. By convention, struct is used for simple data groups.
Why make data members private?
Encapsulation lets the class enforce rules (like no negative balance) and change its internal design later without breaking code that uses it.