This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Sunday, February 19, 2023

what is abstract class? Write a program in C++ that implements the concept of multilevel inheritance.

An abstract class is a class that cannot be instantiated on its own, but instead is meant to be used as a base class for other classes. An abstract class contains at least one pure virtual functions, which is a virtual function that has no implementation in the base class and is meant to be overridden by derived classes.

Now, let's write a program in C++ that implements the concept of multilevel inheritance, which is a type of inheritance where a derived class is created from another derived class.

#include <iostream>

using namespace std;

class Animal {
    public:
        void eat() {
            cout << "Animal is eating." << endl;
        }
};

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

class GermanShepherd : public Dog {
    public:
        void guard() {
            cout << "German Shepherd is guarding." << endl;
        }
};

int main() {
    GermanShepherd gs;
    gs.eat();    // Inherited from Animal class
    gs.bark();   // Inherited from Dog class
    gs.guard();  // Defined in GermanShepherd class
    return 0;
}

In this program, we define a base class 'Animal' that has a member function 'eat()', which prints a message indicating that an animal is eating. We then define a derived class 'Dog' that inherits from the 'Animal' class and has a member function 'bark()', which prints a message indicating that a dog is barking. Finally, we define a derived class 'GermanShepherd' that inherits from the 'Dog' class and has a member function 'guard()', which prints a message indicating that a German Shepherd is guarding.

In the 'main()' function, we create an object 'gs' of the 'GermanShepherd' class and call the member functions 'eat()', 'bark()', and 'guard()' on it. Since the 'GermanShepherd' class inherits from the 'Dog' class, which in turn inherits from the 'Animal' class, it has access to all the member functions defined in those classes.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget