cpp

inheritance

01_inheritance.cpp⚙️
/**
 * ============================================================
 * C++ INHERITANCE
 * ============================================================
 * 
 * This file covers:
 * - What is inheritance
 * - Base and derived classes
 * - Access specifiers in inheritance
 * - Constructor/destructor chain
 * - Method overriding
 * - Types of inheritance
 * 
 * Compile: g++ -std=c++17 -Wall 01_inheritance.cpp -o inheritance
 * Run: ./inheritance
 * 
 * ============================================================
 */

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// ============================================================
// PART 1: BASIC INHERITANCE
// ============================================================

// Base class (Parent/Superclass)
class Animal {
protected:
    string name;
    int age;
    
public:
    Animal(const string& n = "Unknown", int a = 0) : name(n), age(a) {
        cout << "  Animal constructor for " << name << endl;
    }
    
    ~Animal() {
        cout << "  Animal destructor for " << name << endl;
    }
    
    void eat() const {
        cout << name << " is eating." << endl;
    }
    
    void sleep() const {
        cout << name << " is sleeping." << endl;
    }
    
    string getName() const { return name; }
    int getAge() const { return age; }
    
    void display() const {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Derived class (Child/Subclass)
class Dog : public Animal {
private:
    string breed;
    
public:
    Dog(const string& n, int a, const string& b) 
        : Animal(n, a), breed(b) {  // Call base constructor
        cout << "  Dog constructor for " << name << endl;
    }
    
    ~Dog() {
        cout << "  Dog destructor for " << name << endl;
    }
    
    // New method specific to Dog
    void bark() const {
        cout << name << " says: Woof! Woof!" << endl;
    }
    
    void fetch() const {
        cout << name << " is fetching the ball." << endl;
    }
    
    // Extended display
    void display() const {
        Animal::display();  // Call base class method
        cout << "Breed: " << breed << endl;
    }
};

class Cat : public Animal {
private:
    bool isIndoor;
    
public:
    Cat(const string& n, int a, bool indoor = true) 
        : Animal(n, a), isIndoor(indoor) {
        cout << "  Cat constructor for " << name << endl;
    }
    
    ~Cat() {
        cout << "  Cat destructor for " << name << endl;
    }
    
    void meow() const {
        cout << name << " says: Meow!" << endl;
    }
    
    void scratch() const {
        cout << name << " is scratching the furniture." << endl;
    }
    
    void display() const {
        Animal::display();
        cout << "Indoor: " << (isIndoor ? "Yes" : "No") << endl;
    }
};

// ============================================================
// PART 2: ACCESS SPECIFIERS IN INHERITANCE
// ============================================================

class Base {
public:
    int publicVar = 1;
    void publicMethod() { cout << "Public method" << endl; }
    
protected:
    int protectedVar = 2;
    void protectedMethod() { cout << "Protected method" << endl; }
    
private:
    int privateVar = 3;
    void privateMethod() { cout << "Private method" << endl; }
};

// Public inheritance: public stays public, protected stays protected
class PublicDerived : public Base {
public:
    void test() {
        publicVar = 10;       // OK: public
        protectedVar = 20;    // OK: protected accessible in derived
        // privateVar = 30;   // ERROR: private not accessible
        
        publicMethod();       // OK
        protectedMethod();    // OK
        // privateMethod();   // ERROR
    }
};

// Protected inheritance: public becomes protected, protected stays protected
class ProtectedDerived : protected Base {
public:
    void test() {
        publicVar = 10;       // OK: now protected in this class
        protectedVar = 20;    // OK: still protected
    }
};

// Private inheritance: everything becomes private
class PrivateDerived : private Base {
public:
    void test() {
        publicVar = 10;       // OK: now private in this class
        protectedVar = 20;    // OK: now private in this class
    }
};

// ============================================================
// PART 3: EMPLOYEE HIERARCHY EXAMPLE
// ============================================================

class Employee {
protected:
    int id;
    string name;
    double baseSalary;
    
public:
    Employee(int i, const string& n, double salary)
        : id(i), name(n), baseSalary(salary) {}
    
    virtual ~Employee() = default;
    
    int getId() const { return id; }
    string getName() const { return name; }
    
    virtual double calculatePay() const {
        return baseSalary;
    }
    
    virtual void display() const {
        cout << "ID: " << id << endl;
        cout << "Name: " << name << endl;
        cout << "Base Salary: $" << baseSalary << endl;
    }
};

class Manager : public Employee {
private:
    double bonus;
    int teamSize;
    
public:
    Manager(int i, const string& n, double salary, double b, int team)
        : Employee(i, n, salary), bonus(b), teamSize(team) {}
    
    double calculatePay() const override {
        return baseSalary + bonus;
    }
    
    void display() const override {
        Employee::display();
        cout << "Bonus: $" << bonus << endl;
        cout << "Team Size: " << teamSize << endl;
        cout << "Total Pay: $" << calculatePay() << endl;
    }
    
    void conductMeeting() const {
        cout << name << " is conducting a meeting with " << teamSize << " team members." << endl;
    }
};

class Developer : public Employee {
private:
    string programmingLanguage;
    int overtimeHours;
    double overtimeRate;
    
public:
    Developer(int i, const string& n, double salary, const string& lang, 
              int ot = 0, double otRate = 50.0)
        : Employee(i, n, salary), programmingLanguage(lang), 
          overtimeHours(ot), overtimeRate(otRate) {}
    
    double calculatePay() const override {
        return baseSalary + (overtimeHours * overtimeRate);
    }
    
    void display() const override {
        Employee::display();
        cout << "Language: " << programmingLanguage << endl;
        cout << "Overtime: " << overtimeHours << " hours" << endl;
        cout << "Total Pay: $" << calculatePay() << endl;
    }
    
    void code() const {
        cout << name << " is coding in " << programmingLanguage << "." << endl;
    }
};

class Intern : public Employee {
private:
    string university;
    int monthsRemaining;
    
public:
    Intern(int i, const string& n, double stipend, const string& uni, int months)
        : Employee(i, n, stipend), university(uni), monthsRemaining(months) {}
    
    void display() const override {
        Employee::display();
        cout << "University: " << university << endl;
        cout << "Months Remaining: " << monthsRemaining << endl;
    }
    
    void learn() const {
        cout << name << " is learning and gaining experience." << endl;
    }
};

// ============================================================
// PART 4: MULTILEVEL INHERITANCE
// ============================================================

class Vehicle {
protected:
    string brand;
    int year;
    
public:
    Vehicle(const string& b, int y) : brand(b), year(y) {}
    
    void start() const {
        cout << brand << " is starting." << endl;
    }
    
    void stop() const {
        cout << brand << " is stopping." << endl;
    }
};

class Car : public Vehicle {
protected:
    int numDoors;
    
public:
    Car(const string& b, int y, int doors) : Vehicle(b, y), numDoors(doors) {}
    
    void drive() const {
        cout << brand << " car is driving." << endl;
    }
};

class SportsCar : public Car {
private:
    int topSpeed;
    
public:
    SportsCar(const string& b, int y, int doors, int speed) 
        : Car(b, y, doors), topSpeed(speed) {}
    
    void race() const {
        cout << brand << " sports car racing at " << topSpeed << " mph!" << endl;
    }
    
    void display() const {
        cout << year << " " << brand << endl;
        cout << "Doors: " << numDoors << endl;
        cout << "Top Speed: " << topSpeed << " mph" << endl;
    }
};

// ============================================================
// MAIN FUNCTION
// ============================================================

int main() {
    cout << "============================================" << endl;
    cout << "     C++ INHERITANCE" << endl;
    cout << "============================================" << endl << endl;

    // ========================================================
    // DEMO 1: Basic Inheritance
    // ========================================================
    
    cout << "--- DEMO 1: BASIC INHERITANCE ---" << endl << endl;
    
    cout << "Creating Dog object:" << endl;
    {
        Dog dog("Buddy", 3, "Golden Retriever");
        cout << endl;
        
        // Inherited methods
        dog.eat();
        dog.sleep();
        
        // Dog-specific methods
        dog.bark();
        dog.fetch();
        
        cout << "\nDog info:" << endl;
        dog.display();
        
        cout << "\nDestroying Dog object:" << endl;
    }
    
    cout << endl;

    // ========================================================
    // DEMO 2: Multiple Derived Classes
    // ========================================================
    
    cout << "--- DEMO 2: MULTIPLE DERIVED CLASSES ---" << endl << endl;
    
    cout << "Creating Cat object:" << endl;
    {
        Cat cat("Whiskers", 2, true);
        cout << endl;
        
        cat.eat();
        cat.meow();
        cat.scratch();
        
        cout << "\nCat info:" << endl;
        cat.display();
        
        cout << "\nDestroying Cat object:" << endl;
    }
    
    cout << endl;

    // ========================================================
    // DEMO 3: Access Specifiers
    // ========================================================
    
    cout << "--- DEMO 3: ACCESS SPECIFIERS ---" << endl << endl;
    
    PublicDerived pubDerived;
    pubDerived.publicVar = 100;    // OK: still public
    // pubDerived.protectedVar;    // ERROR: protected
    
    ProtectedDerived protDerived;
    // protDerived.publicVar;      // ERROR: became protected
    
    PrivateDerived privDerived;
    // privDerived.publicVar;      // ERROR: became private
    
    cout << "Inheritance Access Table:" << endl;
    cout << "┌────────────┬────────────┬────────────┬────────────┐" << endl;
    cout << "│ Base       │ Public Inh │ Protected  │ Private    │" << endl;
    cout << "├────────────┼────────────┼────────────┼────────────┤" << endl;
    cout << "│ public     │ public     │ protected  │ private    │" << endl;
    cout << "│ protected  │ protected  │ protected  │ private    │" << endl;
    cout << "│ private    │ N/A        │ N/A        │ N/A        │" << endl;
    cout << "└────────────┴────────────┴────────────┴────────────┘" << endl;
    
    cout << endl;

    // ========================================================
    // DEMO 4: Employee Hierarchy
    // ========================================================
    
    cout << "--- DEMO 4: EMPLOYEE HIERARCHY ---" << endl << endl;
    
    Manager mgr(101, "Alice Johnson", 80000, 10000, 5);
    Developer dev(102, "Bob Smith", 70000, "C++", 20, 75);
    Intern intern(103, "Charlie Brown", 2000, "MIT", 3);
    
    cout << "=== Manager ===" << endl;
    mgr.display();
    mgr.conductMeeting();
    
    cout << "\n=== Developer ===" << endl;
    dev.display();
    dev.code();
    
    cout << "\n=== Intern ===" << endl;
    intern.display();
    intern.learn();
    
    cout << endl;

    // ========================================================
    // DEMO 5: Multilevel Inheritance
    // ========================================================
    
    cout << "--- DEMO 5: MULTILEVEL INHERITANCE ---" << endl << endl;
    
    SportsCar ferrari("Ferrari", 2024, 2, 200);
    
    // Methods from Vehicle (grandparent)
    ferrari.start();
    
    // Methods from Car (parent)
    ferrari.drive();
    
    // Methods from SportsCar (current class)
    ferrari.race();
    
    cout << "\nSports Car Info:" << endl;
    ferrari.display();
    
    ferrari.stop();
    
    cout << endl;

    // ========================================================
    // INHERITANCE SUMMARY
    // ========================================================
    
    cout << "--- INHERITANCE CONCEPTS ---" << endl << endl;
    
    cout << "Key Points:" << endl;
    cout << "─────────────────────────────────────────" << endl;
    cout << "1. Derived class inherits from base class" << endl;
    cout << "2. 'public' inheritance is most common" << endl;
    cout << "3. Constructor chain: Base → Derived" << endl;
    cout << "4. Destructor chain: Derived → Base" << endl;
    cout << "5. protected: accessible in derived classes" << endl;
    cout << "6. private: never inherited" << endl;
    
    cout << "\nWhen to use inheritance:" << endl;
    cout << "─────────────────────────────────────────" << endl;
    cout << "• IS-A relationship (Dog IS-A Animal)" << endl;
    cout << "• Code reuse through extension" << endl;
    cout << "• Polymorphic behavior (covered next)" << endl;
    
    cout << "\nInheritance Types:" << endl;
    cout << "─────────────────────────────────────────" << endl;
    cout << "• Single: One parent (most common)" << endl;
    cout << "• Multilevel: Chain of inheritance" << endl;
    cout << "• Multiple: Multiple parents (advanced)" << endl;
    cout << "• Hierarchical: Multiple children, one parent" << endl;

    cout << endl;

    cout << "============================================" << endl;
    cout << "INHERITANCE SUMMARY:" << endl;
    cout << "============================================" << endl;
    cout << "• class Derived : public Base" << endl;
    cout << "• Use protected for derived access" << endl;
    cout << "• Call base constructor in init list" << endl;
    cout << "• Override methods as needed" << endl;
    cout << "• Use Base:: to access hidden methods" << endl;
    cout << "============================================" << endl;

    return 0;
}

// ============================================================
// EXERCISES:
// ============================================================
/*
 * 1. Create a Shape hierarchy:
 *    - Base class Shape with area() and perimeter()
 *    - Derived: Circle, Rectangle, Triangle
 *    - Each implements its own calculations
 * 
 * 2. Create a Vehicle hierarchy:
 *    - Vehicle → MotorVehicle → Car → ElectricCar
 *    - Add appropriate attributes at each level
 * 
 * 3. Create a Person → Student hierarchy:
 *    - Student → UndergraduateStudent, GraduateStudent
 *    - Each with appropriate methods and attributes
 * 
 * 4. Create a BankAccount hierarchy:
 *    - BankAccount → SavingsAccount, CheckingAccount
 *    - Different interest/fee calculations
 */
Inheritance - C++ Tutorial | DeepML