Any way to use a base constructor in a derived class?

After using C # for the last ten or two years, my C ++ is 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...
};

I can't seem to create an instance CDerived.

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

I know that I can explicitly create a derived constructor:

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

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

The base class still needs such arguments anyway. Is there a way to not overwrite these arguments for each derived class, perhaps by “exposing” the base constructor, or should I always do everything I did above?

+4
3

( ++ 11):

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

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
+7

, ++ 11 . , using, :

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

    // Etc...
};

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

++ 11 using , :

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

Live Demo

++ ( ):

Live Demo

error:

Bjarne Stroustrup ++ 11 - :

I said that "A little more than a historical accident does not allow using this to work with the constructor , as well as for a regular member function." C ++ 11 provides this facility

+2
source

Source: https://habr.com/ru/post/1663192/


All Articles