Day 48: Inheritance Oops(Part 5)

๐Ÿ“… Date: Feb 17, 2026

๐Ÿง  Mood: Lazy Genius (Reusing Code) ๐Ÿงฌ

๐Ÿ”ฅ Topic: OOPs Part 5: Inheritance

๐Ÿงฌ What is Inheritance?

In real life, you inherit genes from your parents (Height, Eye Color). You don't create them from scratch.

In C++, Inheritance allows a class (Child) to acquire the properties and behaviors of another class (Parent).

⚡ Why use it?

To follow the DRY Principle (Don't Repeat Yourself). Write the common code once in the Parent class, and reuse it in all Child classes.


๐ŸŒณ Types of Inheritance

C++ supports 5 types of relationships:

  • Single: One Parent → One Child.
  • Multilevel: Grandfather → Father → Child.
  • Multiple: Two Parents → One Child (Confusing, but C++ allows it).
  • Hierarchical: One Parent → Many Children.
  • Hybrid: Mix of all.

๐Ÿ’ป The Syntax (Parent & Child)

Let's create a Human class and inherit it into Student.

#include <iostream>
using namespace std;

// 1. PARENT CLASS (Base Class)
class Human {
    public:
    int height;
    int weight;
    int age;

    void speak() {
        cout << "๐Ÿ—ฃ️ Human is Speaking..." << endl;
    }
};

// 2. CHILD CLASS (Derived Class)
// Syntax: class Child : mode Parent
class Student : public Human {
    public:
    int rollNo;

    void study() {
        cout << "๐Ÿ“š Student is Studying..." << endl;
    }
};

int main() {
    Student s1;
    
    // Accessing Child's own property
    s1.rollNo = 101;

    // ⚡ Accessing Parent's property (Inherited)
    s1.height = 6; 
    s1.speak();    // Output: Human is Speaking...
    s1.study();    // Output: Student is Studying...

    cout << "Student Height: " << s1.height << "ft" << endl;

    return 0;
}

๐Ÿ›ก️ The "Protected" Access Modifier

Remember private data cannot be accessed?
If you want the Child class to access Parent's data but keep it hidden from the world, use protected instead of private.


๐Ÿš€ Day 48 Challenge

  1. Create a class Vehicle with a function drive().
  2. Create a child class Car inheriting Vehicle.
  3. Add a property color to Car.
  4. In main(), create a Car object and call both drive() (from parent) and set its color.

Next Up: Day 49 - Polymorphism (One Name, Many Forms).

No comments:

Post a Comment