csteifel
csteifel

Reputation: 2934

Calling base constructor without directly calling

So I have an "API" in which a user extends a base class the base class contains something like the following

class A {
    A();
    A(int, int);
}

class B : public A {
    B();
}

I would like to be able to call B(int, int) without actually setting up a constructor in B to call it so basically I would like to create sort of like a virtual method for the constructor so that its already set but can be overwritten. Is there any good way to do this or am I going to have to have them include a constructor that calls A(int, int)

Upvotes: 2

Views: 44

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

In C++11, you can use inheriting constructors:

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

This allows you to do the following:

B b(42, 42);

In C++03, you have to do it by hand:

class B : public A {
    B(int i, int j) : A(i,j) {}
    B();
}

Upvotes: 4

Related Questions