Virtual Base Class.

In C++, a virtual base class is a base class that is designed to be shared among multiple derived classes in a class hierarchy. It is used to avoid the “diamond problem” that can occur when multiple inheritance is used.

Let’s consider an example to understand the concept better:

#include <iostream>

class Animal {
public:
    Animal() {
        std::cout << "Animal constructor" << std::endl;
    }

    virtual ~Animal() {
        std::cout << "Animal destructor" << std::endl;
    }
};

class Mammal : public virtual Animal {
public:
    Mammal() {
        std::cout << "Mammal constructor" << std::endl;
    }

    ~Mammal() {
        std::cout << "Mammal destructor" << std::endl;
    }
};

class Bird : public virtual Animal {
public:
    Bird() {
        std::cout << "Bird constructor" << std::endl;
    }

    ~Bird() {
        std::cout << "Bird destructor" << std::endl;
    }
};

class Platypus : public Mammal, public Bird {
public:
    Platypus() {
        std::cout << "Platypus constructor" << std::endl;
    }

    ~Platypus() {
        std::cout << "Platypus destructor" << std::endl;
    }
};

int main() {
    Platypus p;
    return 0;
}

In this example, we have a class hierarchy with Animal as the virtual base class, and Mammal and Bird deriving virtually from it. The Platypus class then derives from both Mammal and Bird.

By using the virtual keyword when inheriting from Animal, we ensure that there is only one instance of the Animal base class in the Platypus object, even though it is indirectly inherited through both Mammal and Bird. This avoids any ambiguity or duplication of the Animal base class.

The output of the program will be:

Animal constructor
Mammal constructor
Bird constructor
Platypus constructor
Platypus destructor
Bird destructor
Mammal destructor
Animal destructor

As you can see, the constructors and destructors are called in the correct order, ensuring that the Animal base class is properly constructed and destructed only once

Leave a Reply

Your email address will not be published. Required fields are marked *