Jonathan Wood
Jonathan Wood

Reputation: 67345

Any way to use base constructor in derived class?

After using C# for the past decade or two, my C++ has gone a little rusty.

If I have the following:

class CBase
{
public:
    CBase(LPCTSTR pszArg1, LPCTSTR pszArg2, LPCTSTR pszArg3);
    virtual ~CBase();

    // Etc...
};

class CDerived : CBase
{
    // Etc...
};

It appears I cannot create an instance of CDerived.

no instance of constructor "CDerived::CDerived" matches the argument list

I know I can create a derived constructor explicitly:

CDerived::CDerived(LPCTSTR pszArg1, LPCTSTR pszArg2, LPCTSTR pszArg3)
    : CBase(pszArg1, pszArg2, pszArg3)
{
}

But that seems like a lot of typing, particularly if I plan to derive many classes from the base class.

The base class still needs those arguments one way or another. Is there a way to not have to rewrite this arguments for every derived class, "exposing" the base constructor perhaps, or must I absolutely always do as I've done above?

Upvotes: 7

Views: 2139

Answers (3)

songyuanyao
songyuanyao

Reputation: 173024

You could use inheriting constructors (since C++11):

class CDerived : public CBase
{
public:
    using CBase::CBase;
    // Etc...
};

Then you could

LPCTSTR pszArg1;
LPCTSTR pszArg2;
LPCTSTR pszArg3;
CDerived d(pszArg1, pszArg2, pszArg3); // initialize CBase subobject by CBase::CBase(LPCTSTR, LPCTSTR LPCTSTR), 
                                       // then default-initialize other members of CDerived

Upvotes: 10

Guillaume Racicot
Guillaume Racicot

Reputation: 41840

Yes, you can do that in C++11 and later. To inherit a base constructor, you must use the using keyword followed by the name of the base class constructor:

struct CBase {
    CBase(LPCTSTR pszArg1, LPCTSTR pszArg2, LPCTSTR pszArg3);
    virtual ~CBase();

    // Etc...
};

struct CDerived : CBase {
    // we use the base constructor
    using CBase::CBase;
};

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 598134

In C++11 and later only, you can use a using statement to inherit the base class's constructors, eg:

class CDerived : public CBase
{
public:
    using CBase::CBase;
};

Live Demo

However, this does not work for constructors in earlier C++ versions (it works for methods, though):

Live Demo

error: using declaration cannot refer to a constructor

From Bjarne Stroustrup's C++11 FAQs - Inherited constructors:

I have said that "Little more than a historical accident prevents using this to work for a constructor as well as for an ordinary member function." C++11 provides that facility

Upvotes: 2

Related Questions