Exploring System Design: Day 3

Aparna SinghAparna Singh
6 min read

🔍 Learning OOP Concepts

🎯 What is Polymorphism?

Polymorphism means “many forms” — the same function or method behaves differently based on the context in which it is called.

In programming, it allows one interface to be used for a general class of actions, with specific behavior determined at runtime or compile-time.


🧍‍♂️ Real-Life Analogy: Human Reaction

Let’s say a person is running:

ContextBehavior
Normal WalkRuns casually
In DangerRuns fast, avoids obstacles
In a RaceRuns with focus, technique, and max speed

➡️ Same action (running), but different behavior based on context.

That’s polymorphism in the real world.


🧠 How It Relates to Programming

In Object-Oriented Programming:

A single method name can behave differently depending on:

  • What parameters are passed (Static Polymorphism)

  • Which object is invoking the method (Dynamic Polymorphism)


Two Types of Polymorphism

1️⃣ Static Polymorphism (Compile-Time)

  • Achieved by: Method Overloading, Operator Overloading

  • Decision Time: At compile-time

  • How: Same method name with different parameters (number/type)

Example: Human Reacts Differently Based on Context

#include <iostream>
using namespace std;

class Human {
public:
    void react() {
        cout << "Human is walking casually.\n";
    }

    void react(string situation) {
        if (situation == "lion")
            cout << "Human is running fast to escape the lion!\n";
        else if (situation == "fire")
            cout << "Human is finding a safe exit from fire!\n";
        else
            cout << "Human is reacting cautiously.\n";
    }

    void react(int speed) {
        cout << "Human is running at " << speed << " km/h.\n";
    }
};

int main() {
    Human h;
    h.react();                 // Normal condition
    h.react("lion");          // Dangerous situation
    h.react(25);              // Speed-based reaction
}

Example: Manual Car Accelerate Overloaded

class ManualCar {
public:
    void accelerate() {
        cout << "Manual car is accelerating slowly.\n";
    }

    void accelerate(int speed) {
        cout << "Manual car is accelerating to " << speed << " km/h.\n";
    }
};

2️⃣ Dynamic Polymorphism (Runtime)

  • Achieved by: Method Overriding (via virtual functions)

  • Decision Time: At runtime using inheritance + late binding

Example: Car Acceleration with Inheritance

cppCopy codeclass Car {
public:
    virtual void accelerate() {
        cout << "The car accelerates in a general way.\n";
    }
};

class ManualCar : public Car {
public:
    void accelerate() override {
        cout << "Manual car accelerates using gear and clutch.\n";
    }
};

class ElectricCar : public Car {
public:
    void accelerate() override {
        cout << "Electric car accelerates silently with electric motor.\n";
    }
};

int main() {
    Car* car1 = new ManualCar();
    Car* car2 = new ElectricCar();

    car1->accelerate();  // ManualCar's version
    car2->accelerate();  // ElectricCar's version

    delete car1;
    delete car2;
}

🎯 Summary Table

TypeHowWhen ResolvedExample
Static PolymorphismMethod/Operator OverloadingCompile-timereact() with different args
Dynamic PolymorphismVirtual Function OverridingRuntimeaccelerate() in subclasses

⚙️ Operator Overloading in C++

What is it?

Customizing behavior of operators (e.g. +, -, ==) for user-defined types.

Example: Complex Number Addition

class Complex {
public:
    int real, imag;

    Complex(int r = 0, int i = 0) : real(r), imag(i) {}

    Complex operator+(const Complex& other) {
        return Complex(real + other.real, imag + other.imag);
    }

    void display() {
        cout << real << " + " << imag << "i\n";
    }
};

🚫 Languages That Don’t Support Operator Overloading

LanguageSupportReason
JavaTo maintain simplicity and readability
Go (Golang)Avoids abstraction overhead, prefers explicitness
JavaScriptDynamic typing already overloads operators internally

✅ Languages That Support It

LanguageSupport LevelSyntax Style Example
C++Fulloperator+()
PythonFull__add__, __eq__
C#Limitedpublic static Type operator +(Type a, b)
SwiftFullUses static func + (lhs:rhs:)

🚗 Understanding Inheritance in OOP

🎯 What is Inheritance?

Inheritance is an object-oriented concept where a class (child) inherits properties and behaviors (methods) from another class (parent).

It allows for code reuse and a hierarchical relationship between classes.


🧍‍♂️ Real-Life Analogy: Cars

Every Car has:

  • brand

  • model

  • isEngineOn

  • currentSpeed

  • Methods like startEngine() and stopEngine()

Now consider two types of cars:

Manual CarElectric Car
Has GearsNo gears
Uses clutch + gearUses electric motor
currentGear, shiftGear()Unique electric behavior (can be extended)

These specializations are built on top of the common Car. That’s inheritance.


🧠 C++ Code Example: Base and Derived Classes

#include <iostream>
using namespace std;
class Car {
public:
    string brand;
    int model;
    bool isEngineOn;
    int currentSpeed;

    Car(string b, int m) : brand(b), model(m), isEngineOn(false), currentSpeed(0) {}

    void startEngine() {
        isEngineOn = true;
        cout << brand << " engine started.\n";
    }

    void stopEngine() {
        isEngineOn = false;
        currentSpeed = 0;
        cout << brand << " engine stopped.\n";
    }

    void showStatus() {
        cout << "Brand: " << brand << ", Model: " << model 
             << ", Engine: " << (isEngineOn ? "On" : "Off") 
             << ", Speed: " << currentSpeed << " km/h\n";
    }
};

🚘 Derived Class: ManualCar


class ManualCar : public Car {
public:
    int currentGear;

    ManualCar(string b, int m) : Car(b, m), currentGear(1) {}

    void shiftGear(int gear) {
        if (gear >= 1 && gear <= 6) {
            currentGear = gear;
            cout << brand << " shifted to gear " << gear << ".\n";
        } else {
            cout << "Invalid gear!\n";
        }
    }

    void accelerate() {
        if (isEngineOn) {
            currentSpeed += 10;
            cout << brand << " accelerated. Speed: " << currentSpeed << " km/h\n";
        } else {
            cout << "Start the engine first.\n";
        }
    }
};

⚡ Derived Class: ElectricCar


class ElectricCar : public Car {
public:
    ElectricCar(string b, int m) : Car(b, m) {}

    void accelerate() {
        if (isEngineOn) {
            currentSpeed += 15;
            cout << brand << " (electric) accelerated silently. Speed: " << currentSpeed << " km/h\n";
        } else {
            cout << "Start the engine first.\n";
        }
    }
};

🧪 Example Usage

    int main() {
    ManualCar manual("Toyota", 2020);
    manual.startEngine();
    manual.shiftGear(2);
    manual.accelerate();
    manual.showStatus();
    manual.stopEngine();

    cout << "---------------------\n";

    ElectricCar tesla("Tesla", 2023);
    tesla.startEngine();
    tesla.accelerate();
    tesla.showStatus();
    tesla.stopEngine();

    return 0;
}

✅ Summary

ConceptDescription
InheritanceChild classes inherit features from base
ManualCarAdds gears, shiftGear method
ElectricCarUses electric-specific behavior
Code ReusabilityCommon functions like start/stop engine used in all cars

0
Subscribe to my newsletter

Read articles from Aparna Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aparna Singh
Aparna Singh

👨‍💻 Full-stack web developer | Learning System Design 🚀 Passionate about building smart solutions & solving real-world problems 🧠 Love exploring EdTech, AI, and smart city innovations 🛠️ Hackathon enthusiast | Enjoy working on impactful, fast-paced projects 📚 Documenting my dev journey through blogs & code snippets 🎯 Aiming to become a confident tech leader & open-source contributor 🤝 Let’s connect, learn, and grow together in tech!