GK SOLUTIONS
AI • IoT • Arduino • Projects & Tutorials
DEFEAT THE FEAR
← Back to All Lessons

🧬 Lesson 5: Inheritance (Hierarchies)

⏱️ Estimated time: 30 minutes | Difficulty: Intermediate

Parent and Child

Inheritance allows a class (child) to inherit properties and methods from another class (parent), promoting code reuse and logical grouping.

What is Inheritance?

Inheritance lets a child class inherit properties and methods from a parent class, promoting code reuse.

#include <iostream>
using namespace std;

// Base class (parent)
class Animal {
public:
    string name;
    void eat() { cout << name << " is eating" << endl; }
    void sleep() { cout << name << " is sleeping" << endl; }
};

// Derived class (child)
class Dog : public Animal {
public:
    void bark() { cout << name << " says Woof!" << endl; }
};

class Cat : public Animal {
public:
    void meow() { cout << name << " says Meow!" << endl; }
};

int main() {
    Dog d;
    d.name = "Buddy";
    d.eat();    // Inherited from Animal
    d.bark();   // Dog's own method

    Cat c;
    c.name = "Whiskers";
    c.eat();    // Inherited
    c.meow();   // Cat's own method
    return 0;
}

Constructor Inheritance

class Shape {
protected:
    string color;
public:
    Shape(string c) : color(c) {}
    void showColor() { cout << "Color: " << color << endl; }
};

class Circle : public Shape {
    double radius;
public:
    Circle(string c, double r) : Shape(c), radius(r) {}
    double area() { return 3.14159 * radius * radius; }
};

int main() {
    Circle c("Red", 5.0);
    c.showColor();  // Color: Red
    cout << "Area: " << c.area() << endl;
    return 0;
}

Multiple Inheritance

class Flyable {
public:
    void fly() { cout << "Flying!" << endl; }
};

class Swimmable {
public:
    void swim() { cout << "Swimming!" << endl; }
};

// Duck can both fly AND swim
class Duck : public Flyable, public Swimmable {
public:
    void quack() { cout << "Quack!" << endl; }
};

✅ Quick Quiz

❓ What keyword is used for inheritance?

❓ Can C++ do multiple inheritance?

❓ What does 'protected' access mean?

← Previous Next: Polymorphism →