Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically implementing a constructor which calls a specific base class constructor

Tags:

c++

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?

like image 782
Bwmat Avatar asked Jan 10 '23 02:01

Bwmat


2 Answers

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.

like image 76
juanchopanza Avatar answered Jan 15 '23 19:01

juanchopanza


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.

like image 39
Lightness Races in Orbit Avatar answered Jan 15 '23 21:01

Lightness Races in Orbit