OOP
Classes and Objects
Build your own types with C++ classes, constructors, destructors, and access control.
Classes in C++
A class defines a blueprint for objects. It encapsulates data (member variables) and behavior (member functions/methods).
Access Specifiers
public: Accessible from anywhereprivate: Only accessible within the class (default for classes)protected: Accessible within the class and derived classes
Constructors and Destructors
- Constructor: Called when an object is created. Initializes member variables.
- Destructor: Called when an object is destroyed. Frees resources.
The Rule of Three/Five
If you define a destructor, copy constructor, or copy assignment operator, you likely need to define all three (or five with move semantics in C++11).
Example
cpp
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string owner;
double balance;
int accountNumber;
static int nextAccountNumber; // shared across all instances
public:
// Constructor with initializer list
BankAccount(const string& ownerName, double initialBalance)
: owner(ownerName), balance(initialBalance),
accountNumber(nextAccountNumber++) {
cout << "Account #" << accountNumber << " created for " << owner << endl;
}
// Destructor
~BankAccount() {
cout << "Account #" << accountNumber << " closed" << endl;
}
// Member functions
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
}
return false;
}
// Getter (const method - doesn't modify the object)
double getBalance() const { return balance; }
string getOwner() const { return owner; }
// Static method
static int getTotalAccounts() { return nextAccountNumber; }
};
// Initialize static member
int BankAccount::nextAccountNumber = 1001;
int main() {
BankAccount alice("Alice", 1000.0);
BankAccount bob("Bob", 500.0);
alice.deposit(250.0);
cout << alice.getOwner() << " balance: " << alice.getBalance() << endl;
if (!bob.withdraw(600.0)) {
cout << "Insufficient funds!" << endl;
}
cout << "Total accounts: " << BankAccount::getTotalAccounts() << endl;
return 0;
}Try it yourself — CPP