How to Multilevel inheritance in C++ ?


Multilevel inheritance is a type of inheritance in which a derived class is created from another derived class. In other words, a class can be derived from a derived class. Here's an example of how to implement multilevel inheritance in C++:

// Base class
class Animal {
public:
    void eat() {
        cout << "I can eat!" << endl;
    }
};

// Derived class 1
class Dog : public Animal {
public:
    void bark() {
        cout << "I can bark!" << endl;
    }
};

// Derived class 2
class Bulldog : public Dog {
public:
    void guard() {
        cout << "I can guard!" << endl;
    }
};

int main() {
    Bulldog b;
    b.eat(); // Output: I can eat!
    b.bark(); // Output: I can bark!
    b.guard(); // Output: I can guard!
    return 0;
}

In this example, the Animal class is the base class, the Dog class is derived from the Animal class, and the Bulldog class is derived from the Dog class. The Bulldog class inherits all the properties and methods of the Animal and Dog classes, and it also has its own method guard().

Another example of multilevel inheritance is:

// Base class
class Person {
public:
    void introduce() {
        cout << "Hi, I am a person!" << endl;
    }
};

// Derived class 1
class Student : public Person {
public:
    void study() {
        cout << "I can study!" << endl;
    }
};

// Derived class 2
class Undergraduate : public Student {
public:
    void party() {
        cout << "I can party!" << endl;
    }
};

int main() {
    Undergraduate u;
    u.introduce(); // Output: Hi, I am a person!
    u.study(); // Output: I can study!
    u.party(); // Output: I can party!
    return 0;
}

In this example, the Person class is the base class, the Student class is derived from the Person class, and the Undergraduate class is derived from the Student class. The Undergraduate class inherits all the properties and methods of the Person and Student classes, and it also has its own method party().



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.