Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate derived classes without having to rewrite code?

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

like image 977
lezebulon Avatar asked Dec 28 '22 11:12

lezebulon


2 Answers

C++11 has a way:

class A {
public:
    A(int i);
};

class B : A {
public:
    using A::A; // use A's constructors
};
like image 190
Pubby Avatar answered Feb 13 '23 03:02

Pubby


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

like image 29
Tom Avatar answered Feb 13 '23 02:02

Tom