Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid boilerplate code constructors?

Let's have class like this:

struct Base {
  Base() { ... }
  Base(int) { ... }
  Base(int,string) { ... }
  ...
};

I'd like to inherit many classes from Base, so I write

struct Son : public Base {
  Son() : Base() { }
  Son(int) : Base(int) { }
  Son(int,string) : Base(int,string) { }
};

struct Daughter : public Base {
  Daughter() : Base() { }
  Daughter(int) : Base(int) { }
  Daughter(int,string) : Base(int,string) { }
};

and I don't need to add any code to child's constructors. Is it possible to inherit them implicitly? To call them the same way like in Base, just change the name? Preprocessor can be abused here, but is there any other workaround?

like image 308
Jan Turoň Avatar asked May 23 '12 11:05

Jan Turoň


People also ask

What does boilerplate mean in coding?

In computer programming, boilerplate code or boilerplate refers to sections of code that have to be included in many places with little or no alteration. It is often used when referring to languages that are considered verbose, i.e. the programmer must write a lot of code to do minimal jobs.

Does Spring remove the boilerplate code?

Spring Data JPA allows us to define derived methods that read, update or delete records from the database. This is very helpful as it reduces the boilerplate code from the data access layer.

Which helps in reducing a lot of boilerplate code?

The need for boilerplate can be reduced through high-level mechanisms such as metaprogramming (which has the computer automatically write the needed boilerplate code or insert it at compile time), convention over configuration (which provides good default values, reducing the need to specify program details in every ...


1 Answers

In a C++11 compliant compiler (§12.9 in the standard), you can actually do this quite easily:

struct Son : public Base {
  using Base::Base;
};

This inherits all constructors from Base and is equivalent to your code for class Son.

like image 83
Gorpik Avatar answered Nov 08 '22 09:11

Gorpik