SyntaxStudy
Sign Up
C++ Classes and Objects in C++
C++ Beginner 12 min read

Classes and Objects in C++

C++ classes are the foundation of object-oriented programming in C++. A class defines a blueprint for objects, encapsulating data (attributes) and functions (methods) that operate on that data.

Example
#include <iostream>
#include <string>
using namespace std;

class BankAccount {
private:  // encapsulation
    string owner;
    double balance;

public:
    // Constructor
    BankAccount(string name, double initialBalance)
        : owner(name), balance(initialBalance) {}

    // 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;
    }

    double getBalance() const { return balance; }
    string getOwner()   const { return owner; }

    // Operator overloading
    friend ostream& operator<<(ostream& os, const BankAccount& acc) {
        os << acc.owner << ": $" << acc.balance;
        return os;
    }
};

int main() {
    BankAccount acc("Alice", 1000.0);
    acc.deposit(500);
    acc.withdraw(200);
    cout << acc << endl;  // Alice: $1300
}