Classes, Objects, Constructors, Destructors, and Encapsulation
Learn how C++ models objects through classes, data members, member functions, constructors, destructors, and access control.
Inside this chapter
- Defining a Class
- Constructors and Initialization Lists
- Destructors and Lifetime
- const Member Functions
- Design Advice
- Real-World Usage Snapshot
Series navigation
Study the chapters in order for the clearest path from C++ basics to modern ownership, templates, concurrency, performance, and production-ready engineering practices. Use the navigation at the bottom to move smoothly through the full series.
Defining a Class
class BankAccount {
private:
std::string owner;
double balance;
public:
BankAccount(const std::string &ownerName, double initialBalance)
: owner(ownerName), balance(initialBalance) {
}
void deposit(double amount) {
balance += amount;
}
double getBalance() const {
return balance;
}
};
Classes package state and behavior together. Encapsulation keeps implementation details controlled and helps protect invariants.
Constructors and Initialization Lists
Constructors define how objects start life. Initialization lists are often preferred for efficiency and correctness, especially for const members, references, and complex objects.
Destructors and Lifetime
~BankAccount() {
std::cout << "Account object destroyed\n";
}
Destructors run automatically when objects leave scope. This becomes the foundation of RAII, one of the most important resource-management ideas in modern C++.
const Member Functions
Marking member functions as const communicates that they do not modify object state. This improves correctness and allows the functions to be used with const objects.
Design Advice
- Keep class responsibilities focused.
- Hide implementation detail behind public behavior.
- Maintain valid object state through constructors.
- Use const correctness where appropriate.
Real-World Usage Snapshot
C++ applications use classes heavily for domain models, engine components, networking abstractions, data structures, and resource wrappers. Good class design is central to writing maintainable large-scale C++ software.