Constructor got deleted by compiler when I have a virtual method?
10
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:
- Why does the compiler do that?
- 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;
}
c++
virtual
function. I must do some reading. A moment, assuming someone who already knows this trick doesn't come along. – user4581301 Apr 23 at 0:15delete
d; It didn't exist in the first place. Documentation for Aggregate Initialization – user4581301 Apr 23 at 0:24