Tag: hierarchical inheritance c++

  • Inheritance in C++

    Learn Inheritance in C++ with simple examples, syntax, types, and access specifiers. A complete beginner to advanced guide for interviews and exams.

    Inheritance in C++ is an Object-Oriented Programming (OOP) concept where one class (called the derived class) acquires the properties and behavior (variables and functions) of another class (called the base class).

    In simple terms:
    Inheritance allows you to reuse existing code and build new features on top of it.

    Basic Syntax

    
    class BaseClass {
    // data members and member functions
    };
    
    class DerivedClass : access_specifier BaseClass {
    // additional members of derived class
    };

    Example :

    class BaseClass {
    public:
        int a;
    
        void display() {
            cout << "This is base class" << endl;
        }
    };
    
    class DerivedClass : public BaseClass {
    public:
        void show() {
            cout << "This is derived class" << endl;
        }
    };
    

    Example Program

    #include <iostream>
    using namespace std;
    
    class Animal {
    public:
        void eat() {
            cout << "Animal eats" << endl;
        }
    };
    
    class Dog : public Animal {
    public:
        void bark() {
            cout << "Dog barks" << endl;
        }
    };
    
    int main() {
        Dog d;
        d.eat();   // inherited from Animal
        d.bark();  // own function
        return 0;
    }
    

    Output:

    Animal eats
    Dog barks
    

    How Inheritance Works in C++

    1.Base Class is Created

    The base class contains common properties and functions.

    class Animal {
    public:
        void eat() {
            cout << "Animal eats" << endl;
        }
    };
    

    2.Derived Class Inherits Base Class

    The derived class uses : to inherit from the base class.

    class Dog : public Animal {
    public:
        void bark() {
            cout << "Dog barks" << endl;
        }
    };
    

    3.Object of Derived Class is Created

    When you create an object of the derived class, it can access:

    • Its own methods
    • Inherited methods from base class
    int main() {
        Dog d;
        d.eat();   // inherited function
        d.bark();  // own function
    }
    

    Internal Working of Inheritance

    Memory Sharing

    • The derived class object contains base class data + its own data
    • No duplication of code

    Conceptually:

    Dog object = Animal properties + Dog properties
    

    Function Access

    • Derived class can directly use public and protected members
    • Cannot access private members of base class directly

    Constructor Execution Order

    When object is created:

    1. Base class constructor runs first
    2. Derived class constructor runs next
    class A {
    public:
        A() {
            cout << "Base Constructor" << endl;
        }
    };
    
    class B : public A {
    public:
        B() {
            cout << "Derived Constructor" << endl;
        }
    };
    

    Output:

    Base Constructor
    Derived Constructor
    

    Destructor Order (Reverse)

    When object is destroyed:

    1. Derived class destructor runs
    2. Base class destructor runs

    Function Overriding

    Derived class can override base class function

    class A {
    public:
        void show() {
            cout << "Base";
        }
    };
    
    class B : public A {
    public:
        void show() {
            cout << "Derived";
        }
    };
    

    Access Specifiers in C++ Inheritance

    In inheritance, access specifiers define how the base class members are accessible in the derived class.

    Types of Access Specifiers

    public

    • Accessible everywhere
    • Can be used inside and outside the class

    protected

    • Accessible within the class and derived class
    • Not accessible outside

    private

    • Accessible only within the same class
    • Not accessible in derived class directly

    Syntax with Access Specifier

    class DerivedClass : access_specifier BaseClass {
        // code
    };
    

    Example:

    class B : public A
    

    How Access Specifiers Work in Inheritance

    Inheritance TypeBase public →Base protected →Base private →
    publicpublicprotected❌ not accessible
    protectedprotectedprotected❌ not accessible
    privateprivateprivate❌ not accessible

    Example Code

    #include <iostream>
    using namespace std;
    
    class A {
    public:
        int x = 10;
    
    protected:
        int y = 20;
    
    private:
        int z = 30;
    };
    
    class B : public A {
    public:
        void show() {
            cout << x << endl; // ✅ public → accessible
            cout << y << endl; // ✅ protected → accessible
            // cout << z; ❌ private → not accessible
        }
    };
    
    int main() {
        B obj;
        obj.show();
        cout << obj.x; // ✅ public accessible outside
        // cout << obj.y; ❌ not accessible outside
    }
    

    Key Points

    public → accessible everywhere
    protected → accessible in child class only
    private → not accessible in child class

    Default inheritance:

    • class → private inheritance
    • struct → public inheritance

    Real-Life Working Example

    Think of:

    • Parent Class: Vehicle
    • Child Class: Car

    Car automatically gets:

    • speed
    • engine

    But also adds:

    • air conditioning
    • music system

    Why Inheritance is Used in C++

    Benefits

    • Code reusability
    • Reduces duplication
    • Easy maintenance
    • Supports polymorphism
    • Improves readability

    Important Points

    • Inheritance uses : operator
    • Base class constructor executes first
    • Private members are not directly accessible
    • Supports multiple types (single, multiple, multilevel, etc.)
    • Used for “is-a” relationship (Dog is an Animal)

    What is the use of : in C++ Inheritance?

    In C++, the colon : is used to specify inheritance.

    It tells the compiler that:

    “This class is inheriting from another class.”

    Basic Syntax

    class DerivedClass : public BaseClass {
    };
    

    Here:

    • : → means inherit from
    • public → access specifier
    • BaseClass → parent class

    How : Works

    When you write:

    class B : public A {
    };
    

    It means:

    • Class B gets properties and functions of class A
    • B becomes child (derived class)
    • A becomes parent (base class)

    Example

    #include <iostream>
    using namespace std;
    
    class A {
    public:
        void show() {
            cout << "Base class" << endl;
        }
    };
    
    class B : public A {
    };
    
    int main() {
        B obj;
        obj.show();  // inherited using :
    }
    

    Without : → inheritance will NOT happen

    Without : (No Inheritance)

    class B {
    };
    

    Now:

    • B has no relation with A
    • Cannot access A’s functions

    Real Meaning of :

    Think of it like:

    : = “is derived from”
    : = “inherits from”

    Important Uses of :

    1. To inherit a class

    class Child : public Parent

    2. Multiple inheritance

    class C : public A, public B

    3. Access control during inheritance

    class B : private A

    Types of Inheritance in C++

    1. Single Inheritance

    One base class → One derived class

    class A {};
    class B : public A {};

    2. Multiple Inheritance

    One derived class inherits from multiple base classes

    class A {};
    class B {};
    class C : public A, public B {};

    3. Multilevel Inheritance

    Chain of inheritance

    class A {};
    class B : public A {};
    class C : public B {};

    4. Hierarchical Inheritance

    One base class → multiple derived classes

    class A {};
    class B : public A {};
    class C : public A {};

    5. Hybrid Inheritance

    Combination of multiple types (complex structure)

    Access Specifiers in Inheritance

    Inheritance TypePublic MembersProtected MembersPrivate Members
    publicpublicprotectednot accessible
    protectedprotectedprotectednot accessible
    privateprivateprivatenot accessible

    Example:

    class A {
    protected:
        int x;
    };
    
    class B : public A {
    public:
        void set() {
            x = 10; // accessible
        }
    };

    Key Concepts

    1. Code Reusability

    Reuse existing class code → reduces redundancy

    2. Method Overriding

    Derived class can redefine base class function

    class A {
    public:
        void show() {
            cout << "A";
        }
    };
    
    class B : public A {
    public:
        void show() {
            cout << "B";
        }
    };
    

    3. Constructor in Inheritance

    Base class constructor runs first

    class A {
    public:
        A() {
            cout << "Base constructor" << endl;
        }
    };
    
    class B : public A {
    public:
        B() {
            cout << "Derived constructor" << endl;
        }
    };
    

    4. Destructor Order

    Destructor runs in reverse order

    5. protected Keyword

    Allows access in derived classes but not outside

    6. super concept in C++

    C++ uses base class name instead of super

    class B : public A {
    public:
        void show() {
            A::show(); // calling base class function
        }
    };
    

    Advantages of Inheritance

    • ✔ Code reuse
    • ✔ Easy maintenance
    • ✔ Extensibility
    • ✔ Improves readability
    • ✔ Supports polymorphism

    Disadvantages

    • ❌ Tight coupling between classes
    • ❌ Can increase complexity
    • ❌ Improper use leads to errors

    Real-Life Example

    Think of:

    • Vehicle (Base Class)
    • Car, Bike (Derived Classes)

    All share common features like speed, engine, but also have unique features.

    Interview Questions

    1. What is inheritance in C++?
    2. Difference between inheritance and polymorphism?
    3. Types of inheritance?
    4. What is multiple inheritance?
    5. What is diamond problem?
    6. Difference between public, private, protected inheritance?
    7. Constructor order in inheritance?
    8. What is virtual inheritance?

    Summary

    Inheritance is a powerful feature in C++ that allows one class to inherit properties and behavior from another class, making code reusable, scalable, and easier to manage.

    Frequently Asked Questions (FAQs) on Inheritance in C++

    1️⃣ What is inheritance in C++?

    Inheritance is an OOP concept where a derived class acquires properties and functions of a base class.

    2️⃣ Why is inheritance used in C++?

    It is used for:

    • Code reusability
    • Reducing duplication
    • Easy maintenance
    • Extending existing functionality

    3️⃣ What is a base class and derived class?

    • Base class → Parent class
    • Derived class → Child class that inherits from base class

    4️⃣ What does : mean in inheritance?

    The : operator is used to define inheritance between classes.

    5️⃣ What are the types of inheritance in C++?

    • Single
    • Multiple
    • Multilevel
    • Hierarchical
    • Hybrid

    6️⃣ What is single inheritance?

    One derived class inherits from one base class.

    7️⃣ What is multiple inheritance?

    A derived class inherits from more than one base class.

    8️⃣ What is multilevel inheritance?

    A class is derived from another derived class (chain structure).

    9️⃣ What is hierarchical inheritance?

    Multiple classes inherit from the same base class.

    🔟 What is hybrid inheritance?

    Combination of multiple inheritance types.

    1️⃣1️⃣ What are access specifiers in inheritance?

    They control visibility of base class members:

    • public
    • protected
    • private

    1️⃣2️⃣ Can private members be inherited?

    Yes, but they are not directly accessible in derived class.

    1️⃣3️⃣ What is function overriding?

    When a derived class provides its own implementation of a base class function.

    1️⃣4️⃣ What is the order of constructor execution?

    • Base class constructor executes first
    • Then derived class constructor

    1️⃣5️⃣ What is the diamond problem?

    It occurs in multiple inheritance when a class inherits from two classes that have a common base class, causing ambiguity.

    Solution: Virtual inheritance

    For detailed understanding of Platform Devices and Drivers on Linux, refer to the Linux documentation on Platform Devices and Drivers .