How to have default behaviour on a derived class instead of redefining constructor

59 views Asked by At

I noticed that I'm reusing a lot of code in my inheritance hierarchy, and I was wondering if there isn't a better way. I have an Item class from which many other types of item can inherit:

struct Item{ 
    Item(){};
    Item(string name) : name(name){}
    string name;
};

So this is a class that can be created with no name (the default), or a name provided. All is good. But say I have a class inheriting from Item:

struct Book : Item
{
};

I can't then do:

Book harryPotter("Harry Potter");

If I want the same type of behaviour, where I can choose to provide a string or not, I have to do the following:

struct Book : Item
{
    Book(string name) : Item(name) {}   // Set the name in base's initialiser list
    // Or...
    Book(string name) { this->name = name; }  // Set the name in derived's constructor
};

In both cases I then have to write a separate default constructor, as the compiler won't provide one where I've made my own type.

Then, as far as I can see, this will have to be retyped each time I create a new Item type.

And I've realised this problem happens even if I don't want a default constructor, if I want to create a type of Item, I have to explicitly create the constructor for each one?

Edit: Thanks to Sam Varshavchik for this, starting from C++11 you can inherit constructors with:

using Base::Base;
1

There are 1 answers

4
Sam Varshavchik On
struct Book : Item
{
    using Item::Item;
};

This is going to, essentially, inherit all of Item's constructors into Book.