1

Suppose I have:

class A {
public:
        A(int x_) : x(x_) {}
        int x;
};

class B: public A { };
class C: public A { };

With this code, B and C won't have any constructors (other than the copy constructor). I would like to change something in class A (not in B or C) so that both B and C will inherit the constructor of A. Is that possible somehow?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • No, and the reason is that for that to be possible, you'd have to autogenerate code for classes B and C from A. But I'm not sure that I see every possiblity, thus not an answer – WorldSEnder Jan 22 '16 at 14:18
  • 2
    Possible duplicate of [Inheriting constructors](http://stackoverflow.com/questions/347358/inheriting-constructors) – Pixelchemist Jan 22 '16 at 14:25
  • @Pixelchemist: That question asks _why_ the code I've also written down here doesn't result in ctor inheritance. I asked whether it's possible to _add_ something (or change something) to make inheritance happen. So, not a dupe. – einpoklum Jan 22 '16 at 14:33

1 Answers1

8

It is not possible to have them implicitly. You can explicitly have the constructors available via:

class B: public A { using A::A; };
class C: public A { using A::A; };
Pixelchemist
  • 24,090
  • 7
  • 47
  • 71
  • Probably because I had `:` instead of `::` ;-) – Pixelchemist Jan 22 '16 at 14:24
  • That's too bad, but +1 for breaking the bad news to me. Also, your answer could have ended after first period, I know about the rest. But ok. – einpoklum Jan 22 '16 at 14:34
  • 4
    @einpoklum How was Pixelchemist supposed to know that? I think it is great that he offered how you could do it. Remember that answers are not just for you but for everyone else who searches for this. they might not know you can explicitly inherit constructors. – NathanOliver Jan 22 '16 at 14:40
  • @NathanOliver: I did explicitly say I don't want to change anything about B and C. And that's why I gave two subclasses ratheer than one as an example. – einpoklum Jan 22 '16 at 14:58