БезКода
БезКода

Reputation: 75

I want my inherited class to have the same constructor

Because my constructor is just Ent::Ent(string InputID) { ID = InputID; }.

I want this to be the same for all classes that inherit that class.

Everyone says the constructor is different somehow from other functions of inherited class???

Upvotes: 1

Views: 202

Answers (1)

cdhowie
cdhowie

Reputation: 169018

In C++11 you can pull all of the constructors of a parent type into a derived type with the using keyword:

class A
{
public:
    A(int v) : value(v) { }

    int value;
};

class B : public A
{
public:
    using A::A;
};

int main() {
    B b = B(1);
    std::cout << b.value << std::endl;
    return 0;
}

(Demo.)

This will create a set of inheriting constructors in B that call the corresponding constructor in A to initialize the base object.

You must do this in each derived class, but it beats having to write each constructor you want to "inherit" by hand.

Upvotes: 9

Related Questions