Inheriting constructors

suggest change

As a special case, a using-declaration at class scope can refer to the constructors of a direct base class. Those constructors are then inherited by the derived class and can be used to initialize the derived class.

struct Base {
    Base(int x, const char* s);
};
struct Derived1 : Base {
    Derived1(int x, const char* s) : Base(x, s) {}
};
struct Derived2 : Base {
    using Base::Base;
};
int main() {
    Derived1 d1(42, "Hello, world");
    Derived2 d2(42, "Hello, world");
}

In the above code, both Derived1 and Derived2 have constructors that forward the arguments directly to the corresponding constructor of Base. Derived1 performs the forwarding explicitly, while Derived2, using the C++11 feature of inheriting constructors, does so implicitly.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents