Classes & Objects
C++ classes combine data and functions into objects. Key C++ OOP features: constructors/destructors for lifecycle management, operator overloading for intuitive syntax, and RAII for automatic resource management.
45 min•By Priygop Team•Last updated: Feb 2026
OOP Code
Example
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string owner;
double balance;
int id;
static int nextId;
public:
// Constructor with initializer list
BankAccount(const string &owner, double initialBalance = 0.0)
: owner(owner), balance(initialBalance), id(nextId++) {}
// Copy constructor
BankAccount(const BankAccount &other)
: owner(other.owner), balance(other.balance), id(nextId++) {}
// Destructor (called when object goes out of scope)
~BankAccount() {
cout << "Account #" << id << " closed" << endl;
}
// Getters
double getBalance() const { return balance; }
string getOwner() const { return owner; }
// Methods
void deposit(double amount) {
if (amount > 0) balance += amount;
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
return true;
}
return false;
}
// Operator overloading
BankAccount operator+(const BankAccount &other) const {
return BankAccount(owner + " & " + other.owner, balance + other.balance);
}
bool operator>(const BankAccount &other) const {
return balance > other.balance;
}
// Friend function (access private members)
friend ostream &operator<<(ostream &os, const BankAccount &acc) {
os << "[#" << acc.id << "] " << acc.owner << ": $" << acc.balance;
return os;
}
};
int BankAccount::nextId = 1;
int main() {
BankAccount alice("Alice", 1000);
BankAccount bob("Bob", 500);
alice.deposit(250);
bob.withdraw(100);
cout << alice << endl; // Operator<< overload
cout << bob << endl;
if (alice > bob) cout << "Alice has more" << endl;
// RAII: accounts automatically destroyed at end of scope
return 0;
}