C++C++ · Lesson 5 of 9

Classes & OOP

Here's the part that justified calling C++ "C with classes." The original name, by the way, was actually "C with Classes." Creative bunch.

C++
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

class Shape {
public:
    virtual double area() const = 0;      // pure virtual
    virtual double perimeter() const = 0;  // pure virtual
    virtual void describe() const {        // virtual with default
        cout << "Shape with area " << area() << "
";
    }
    virtual ~Shape() = default;  // always have virtual destructor
};

class Circle : public Shape {
    double radius;
public:
    Circle(double r) : radius(r) {}  // initializer list

    double area() const override {
        return M_PI * radius * radius;
    }
    double perimeter() const override {
        return 2 * M_PI * radius;
    }
    void describe() const override {
        cout << "Circle(r=" << radius << ") area=" << area() << "
";
    }
};

class Rectangle : public Shape {
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override { return width * height; }
    double perimeter() const override { return 2 * (width + height); }
};

int main() {
    // Polymorphism via pointers/references
    Shape* shapes[] = {
        new Circle(5.0),
        new Rectangle(4.0, 6.0),
        new Circle(3.0),
    };

    for (Shape* s : shapes) {
        s->describe();
        cout << "  Perimeter: " << s->perimeter() << "
";
    }

    for (Shape* s : shapes) delete s;  // clean up
    return 0;
}
C++
#include <iostream>
#include <string>
using namespace std;

class BankAccount {
    string owner;
    double balance;

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

    // Getter (const — doesn't modify the object)
    double getBalance() const { return balance; }
    const string& getOwner() const { return owner; }

    // Methods
    bool deposit(double amount) {
        if (amount <= 0) return false;
        balance += amount;
        return true;
    }

    bool withdraw(double amount) {
        if (amount <= 0 || amount > balance) return false;
        balance -= amount;
        return true;
    }

    void print() const {
        cout << owner << ": $" << balance << "
";
    }
};

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

    if (!acc.withdraw(9999)) {
        cout << "Insufficient funds
";
    }

    return 0;
}