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:

  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;
}
Share
Improve this question
4
  • That's kind of cool. You can't inherit constructors, so I wonder if that's a bug or some fun little edge... Is this like of Aggregate initialization disabled by the 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:15
  • Ok. Sounds like I was A) right and B) too slow. – user4581301 Apr 23 at 0:19
  • Key point: The constructor did not get deleted; It didn't exist in the first place. Documentation for Aggregate Initialization – user4581301 Apr 23 at 0:24
  • According to my experiments, your code fails to compile in C++17, even without the virtual function. It only compiles in C++20. Perhaps you should make that clear (or add the c++20 tag). – TonyK Apr 23 at 10:54

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

flutter websocket connection issue