Constructor got deleted by compiler when I have a virtual method?

Viewed 717

I came across a situation that can be summarized in the following code snippet. Basically, I would like my classes to inherit constructors. It works, but compilation fails as soon as I have a virtual method defined in C. Apparently the compiler deleted the constructor.

My questions are:

  1. Why does the compiler do that?
  2. I can work around by defining constructors in B and C and delegate eventually to A's constructor. Is there a better way to do this?
#include <iostream>

struct A {
  A() = delete;
  A(int x) : x_(x) {}
  int x_;
};

struct B : public A {
};

struct C : public B {
  // What? defining virtual method kills the inherited constructor
  //virtual void foo() {}
};

int main() {
  C c{10};
  std::cout << "Hello World: " << c.x_ << std::endl;
}
1 Answers

Constructors are inherited only when you explicitly declare the inherited constructors. This is done as follows:

struct B : public A {
    using A::A;
};

struct C : public B {
    using B::B;
};

In your program, you are not using inherited constructors; you are using aggregate initialization. Adding a virtual function makes C no longer an aggregate, so aggregate initialization cannot be used. If you declare inherited constructors, then you can construct C without having to use aggregate initialization.

Related