devxlogo

Use C++0x’s Inheriting Constructors to Reduce Boilerplate Code in Class Hierarchies

Use C++0x’s Inheriting Constructors to Reduce Boilerplate Code in Class Hierarchies

ere’s a common scenario: a base class has multiple constructors, each of which takes a different number of parameters of various types. A derived class has to declare “mirror constructors” with signatures that correspond to the base class constructors. Each mirror constructor merely forwards its arguments to the matching base constructor.

Defining the mirror constructors manually is a laborious and error-prone task, because you must update them whenever the base class’s constructors change. Fortunately, a new C++0x feature called inheriting constructors lets you delegate that task to the compiler.

This 10-Minute Solution shows how inheriting constructors can make your code more secure, easier to maintain, and more readable.

When deriving a class from a base class, you need to define constructors that mirror those of the base class.

Rather than defining the mirror constructors manually, let the compiler generate them using the inheriting constructors feature.

Exemplifying Mirror Constructors

Today, initializing a derived class with exactly the same set of constructors as its base class means you have to write a set of constructors (known as mirror constructors) in the derived class. The sole purpose of those mirror constructors is to forward their arguments to the matching constructor of the base class. This is tedious and causes maintenance problems, as the following listing demonstrates:

struct A1 {   explicit A1(int i);   explicit A1(double d);};struct D1 : A1 {   //manual definitions of mirror ctors    explicit D1(int n): A1(n){}   explicit D1(double d): A1(d){}   private:      int x;};
Author’s Note: The informal term “mirror constructor” refers to a user-defined constructor in a derived class that merely forwards its arguments to a base class constructor with a matching signature.

It’s bad enough to have to do this once, but if you derive another class from D1, there’s no escape from repeating this boilerplate code yet again:

struct E1 : D1 {   //manual definitions of mirror ctors in the derived class    explicit E1(int n): D1(n){}   explicit E1(double d): D1(d){}   private:      int y;};

There’s nothing special about mirror constructors; therefore, delegating their declarations to the compiler will not only make your job easier; it will also make your code more readable, because you need only a single declaration to generate all of the mirror constructors. As a bonus, the automatically generated code will probably be more efficient than handwritten code. The C++0x inheriting constructors feature solves this problem.

The solution lies in a special type of using declaration that names the base class constructor in the derived class. This using declaration implicitly declares a set of inheriting constructors in the derived class. Inheriting constructors are similar to mirror constructors except that the compiler declares them rather than the programmer. As with other implicitly-declared constructors, inheriting constructors are defined implicitly only if they are used in the program. Here’s a modified version of D1 with inheriting constructors:

struct D1 : A1 {   using A1::A1; //inheriting ctors declaration   private:      int x;};

The using declaration in the preceding code is what makes this work. The line using A1::A1; instructs the compiler to implicitly declare two inheriting constructors in D1 whose signatures, explicitness, access, exception specifications, and presence or absence of constexpr and =delete are identical to those of A1’s two constructors. The inheriting constructors forward their arguments to the base class constructors using rvalue references. Notice that an implicitly defined inheriting constructor doesn’t initialize user-declared data members of the derived class; such data members undergo default initialization, as do all data members that have no explicit initializer:

D1 d(10); //OK. d.x has an indeterminate value

The definition of d causes the compiler to implicitly define the inheriting constructor D1(int) that was already implicitly-declared along with D1(double) when the compiler encountered the using A1::A1; declaration inside D1.

The implicitly defined inheriting constructor D1(int) forwards its argument to the matching B1(int) constructor. Similarly, the following code causes the compiler to implicitly define the D1(double) constructor, which forwards the argument 8.99 to A1(double), leaving d.x with no explicit initializer.

D1 d2(8.99); //OK, d.x isn't initialized

Lastly, the following line is ill-formed because D1 has no default constructor:

D1 d3; //error

Overriding Inheriting Constructors

As always, you can still add new constructors to a derived class, even one that uses inheriting constructors. If a user-declared constructor and an implicitly declared inheriting constructor have the same signature, the user-declared constructor takes precedence—effectively hiding the inheriting constructor with the same signature. Here’s an example:

struct D1 : A1 {   using A1::A1;//explicit D1(int); explicit D1( double);   //a user-defined ctor hides the inherited ctor D1(int)   explicit D1(int j): A1(0), x(j) {}   private:      int x;};D1 d4(0); //OK, invokes D1(int n): A1(0),x(n) {}

Handling Multiple Inheritance

When a derived class has two or more immediate base classes, you can selectively state which base class’s constructors to inherit using this syntax:

struct B1 {   B1(char);};struct B2 {   B2(double);   B2(int);};struct D1 : B1, B2 {   using B1::B1; //  D1(char)   using B2::B2;  // D1(double), D1(int)};D1 d('c'); //OK, invokes D1(char)

In certain cases, multiple inheritance can lead to ambiguity. Suppose you have two base classes that declare constructors with identical signatures. Inheriting these constructors will cause an error:

struct C1 {   C1(int);   C1(double);};struct C2 {   C2(int);};struct D1 : C1, C2 {   using C1::C1; //  D1(int), D1(double)   using C2::C2;  // D1(int) //conflicts with D(int) above};D1 d(5); //error, should this call C1(1) or C2(1)?

In this situation, because a user-declared constructor supersedes any implicit constructor declaration with the same signature, you can avoid the ambiguity by declaring the problematic constructor explicitly:

struct C1 {   C1(int);   C1(double);};struct C2 {   C2(int);};struct D1 : C1, C2 {   using C1::C1; //  D1(int), D1(double)   using C2::C2;  // D1(int)    D1(int n): C1(n), C2(n), x(n) {} //override D(int)   private:      int x;};D1 d(5); //OK, calling user-defined ctor

Status and Support

Do not confuse inheriting constructors with delegating constructors; the latter apply only to constructors within the same class. The inheriting constructors proposal has already been voted into the C++0x Working Draft, so compiler vendors should start supporting this feature soon.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist