简体   繁体   中英

Providing base class constructor parameters when creating a derived class instance

Is there a way to provide constructor parameters to a base class when new-ing a derived class instance? (That is, when the base class constructor has default values for these parameters)

Eg

class Base
{
public:
 Base::Base( string name = "" )
 : m_name( name ) {};

private
 string m_name;
};

class Derived : public Base
{
public:
 Derived::Derived() {};
};

Then I need to do something like this:

void main()
{
 Base* instance = new Derived( "Jeff" );
};

This obviously doesn't work. Is there a way to new a derived instance and provide a constructor parameter to it's base without having to provide that parameter in the derived class constructor.

Is there a way to new a derived instance and provide a constructor parameter to it's base without having to provide that parameter in the derived class constructor.

No.

Your derived-class constructor needs to take the arguments, and explicitly pass them down to the base-class constructor.

class Derived : public Base
{
public:
 Derived::Derived(string name) : Base(name) {};
};

This is the case regardless of whether you're using new or not.

You can't do it if you want distinct names into base class. however distinct name is not a criteria, you can do it using passing constant literals as:

class Base
{
public:
 Base::Base( string name = "" )
 : m_name( name ) {};

private
 string m_name;
};

class Derived : public Base
{
public:
 Derived::Derived() : Base ("Jeff")    {};
 Derived::Derived(string &name) : Base (name) {};
};

OR pass default value to Derived class constructor.

class Derived : public Base
    {
    public:
     Derived::Derived(string name = "Jeff") : Base (name) {};
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM