Bwmat
Bwmat

Reputation: 4578

Automatically implementing a constructor which calls a specific base class constructor

class A
{
    A(int a);
};

class B : public A
{
    using A::A; // Shorthand for B(int b) : A(b) {}?
};

int main()
{
    B b(3);

    return 0;
}

Is there some way to accomplish what the above program seeks to (to make B have a constructor with the same parameter's as a base class')? Is that the correct syntax for it?

If so, is it a C++11/14 feature, or can it be done in C++03?

Upvotes: 4

Views: 116

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385174

Yes, exactly like that (once I cleaned up your unrelated errors):

struct A
{
    A(int a) {}
};

struct B : A
{
    using A::A; // Shorthand for B(int b) : A(b) {}?
};

int main()
{
    B b(3);
}

(live demo)

These are called inheriting constructors, and are new since C++11.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227418

Is there some way to accomplish what the above program seeks to (to make B have a constructor with the same parameter's as a base class')?

Yes, there is. Using inheriting constructors:

using A::A;

Is that the correct syntax for it?

Yes.

If so, is it a C++11/14 feature, or can it be done in C++03?

This feature was introduced in C++11. It is not valid in C++03.

For more information, see the relevant section of this using declaration reference.

Upvotes: 6

Related Questions