~/okanakyuz
← all posts

Diamond Inheritance

Using virtual inheritance in C++ so a class that appears twice in a diamond hierarchy has only one shared base subobject.

7 March 2020updated 25 November 20261 min read

Diamond shaped class hierarchy

When two classes inherit from the same base and a third class inherits from both of them, we get a diamond. Without anything special, TopClass would contain two separate RootOfAll objects. Using the virtual keyword on the base classes creates one and only one copy.

#include <iostream>
#include <memory>

class RootOfAll {
public:
    RootOfAll(){
        std::cout << "RootOfAll" << std::endl;
    }
    ~RootOfAll(){
        std::cout << "~RootOfAll" << std::endl;
    }
};

// create one copy
class MidLeft: virtual public RootOfAll{
public:
    MidLeft(){
        std::cout << "MidLeft" << std::endl;
    }
    ~MidLeft(){
        std::cout << "~MidLeft" << std::endl;
    }
};

// create one copy
class MidRight: virtual public RootOfAll{
public:
    MidRight(){
        std::cout << "MidRight" << std::endl;
    }
    ~MidRight(){
        std::cout << "~MidRight" << std::endl;
    }
};

class TopClass: public MidLeft, public MidRight{
public:
    TopClass(){
        std::cout << "TopClass" << std::endl;
    }
    ~TopClass(){
        std::cout << "~TopClass" << std::endl;
    }
};

int main()
{
    std::unique_ptr<TopClass> p = std::make_unique<TopClass>();

    return 0;
}

The output shows RootOfAll only once. If you remove virtual from MidLeft and MidRight, it is printed twice, and a conversion from TopClass* to RootOfAll* becomes ambiguous.

One more thing: a virtual base is constructed by the most derived class. So if RootOfAll had a constructor with parameters, TopClass would have to call it directly in its initializer list; the calls in MidLeft and MidRight are ignored when you create a TopClass.