Search code examples
c++inheritancevirtual-functions

Inheritance mess with pure virtual functions, any way to not have to re-define them all?


So I found myself in a bit of a mess of a class hierarchy.

I have code that looks a bit like that, oversimplified:

#include <iostream>

struct Parent {
  virtual void pureVirtual() = 0;
};

struct Child : public Parent {
  void pureVirtual() override {
    std::cout << "Child::pureVirtual()" << std::endl;
  }
};

struct Brother: public Parent {
};

struct GrandChild : public Child, public Brother {
};

GrandChild test;

The compilation fails with:

object of abstract class type "GrandChild" is not allowed: -- pure virtual function "Parent::pureVirtual" has no overriderC/C++(322)

I don't fully understand why the implementation of pureVirtual is not inherited by GrandChild from Child.

In practice, I have tons of pure-virtual functions to "re-implement", that is, just writing lines like:

struct GrandChild : public Child, public Brother {
  void pureVirtual() override {
    Child::pureVirtual();
  }
};

I would have expected the compilator to automatically use the implementation from Child.

Is there any sort of trick I can use to tell the compiler that I am gonna re-use all the implementations from Child?

Anyway I probably have to think of a better design, but this got me interested if there are easy solutions.


Solution

  • The issue is that you actually are getting two pureVirtual functions. C++ isn't smart enough to merge the two by default. You can use virtual inheritance to force the behavior.

    #include <iostream>
    
    struct Parent {
      virtual void pureVirtual() = 0;
    };
    
    struct Child : virtual public Parent {
      void pureVirtual() override {
        std::cout << "Child::pureVirtual()" << std::endl;
      }
    };
    
    struct Brother : virtual public Parent {};
    
    struct GrandChild : public Child, public Brother {};
    
    int main() {
      GrandChild test;
    }