lezebulon
lezebulon

Reputation: 7994

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

Upvotes: 4

Views: 152

Answers (3)

andrewmag
andrewmag

Reputation: 262

as user491704 said it should be something like this

class mother {
public:
 mother (int a)
 {}
 };

class son : public mother {
public:
 son (int a) : mother (a)
 { }
   };

Here is a link for the Tutorial

Upvotes: 2

Tom
Tom

Reputation: 3063

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

Upvotes: 2

Pubby
Pubby

Reputation: 53037

C++11 has a way:

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

class B : A {
public:
    using A::A; // use A's constructors
};

Upvotes: 6

Related Questions