Let's say I have a:
class A {
A(int i);
};
class B : A {
};
I cannot instanciate B(3) for instance, as this constructor is not defined. Is there a way to instanciate a B object that would use the A constructor, without having to add "trivial" code in all derived classes? thanks
thanks
C++11 has a way:
class A {
public:
A(int i);
};
class B : A {
public:
using A::A; // use A's constructors
};
If you're using C++03 this is the best thing I can think of in your situation:
class A {
public:
A(int x) { ... }
};
class B : public A {
public:
B(int x) : A(x) { ... }
}
You may also want to check out the link below, which is a C# question but contains a more detailed answer regarding why constructors can act this way:
C# - Making all derived classes call the base class constructor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With