Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is possible to have virtual inheritance for class not providing default constructor?

The present diamond diagram (the simplest one with the only change of no default constructor provided) does not compile (g++ 4.4.3).

class A {
 public: 
  A(int ) {}
};
class B : virtual public A {
 public:
  B(int i) : A(i) {}
};
class C : virtual public A {
 public:
  C(int i) : A(i) {}
};
class D : public B, public C {
 public:
  D(int i) : B(i), C(i) {}
};

Thanks, Francesco

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to call A's constructor explicitly here

 D(int i) : A(i), B(i), C(i) {}

virtual base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base?

If the most derived class being constructed does not list it in its member initalization list then the virtual base class is initialized with its default constructor which must exist and be accessible.

Shamelessly copied from here :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...