0

Here is perfectly valid code in C++

class A {
public:
    A(int a) {}
};


class B : A {
public:
    B(int a) : A(a) {}
};

class C : B {

    C(int a) : B(a) {}
};

However, when I change inheritance of class B to virtual:

class B : virtual A {
public:
    B(int a) : A(a) {}
};

I get

$ g++ som.h
som.h: In constructor ‘C::C(int)’:
som.h:14:16: error: no matching function for call to ‘A::A()’
C(int a) : B(a) {}
              ^

The strangest is on my friend's PC it compiles (she has g++ 7.3 version and ubuntu 18). I have g++ 5.5 and ubuntu 16.

Could someone explain me why does this happen?

kosciej16
  • 6,294
  • 1
  • 18
  • 29

1 Answers1

0

you need :

class C : public B {
public:
   C(int a) : A(a), B(a) {} // in that order
};

as r3mus n0x says in remark, the most derived class should initialize the virtual base regardless whether inheritance is diamond or not.

morality : if you don't have a diamond do not use virtual inheritance

bruno
  • 32,421
  • 7
  • 25
  • 37