marcoo
marcoo

Reputation: 869

Convert from base class to a dervied class

I am trying to convert from a base class to a derived class. I have the following constructor, however, the compiler complains with:

no matching function for call to ‘baseObject::baseObject()’

constructor:

derivedObject(const baseObject &base, const std::string &extra1)
{
    baseparameter1 = base.baseparameter1;
    baseparameter2 = base.baseparameter2;
    extraparameter1 = extra1;
}

Any advice?

Upvotes: 1

Views: 68

Answers (2)

aschepler
aschepler

Reputation: 72271

Every constructor begins by initializing all base classes and direct members, before you get to the {. Instead of using assignments in the body, use a member initializer list:

derivedObject(const baseObject &base, const std::string &extra1)
    : baseObject(base),        // Calls the baseObject copy constructor
      extraParameter1(extra1)  // Initialize the direct member
{
}

This is better style and also avoids problems like the one you ran into.

Upvotes: 2

sheu
sheu

Reputation: 5763

edit: baseObject copy construction.

Since you haven't defined a default constructor for your baseObject, the compiler can't construct a derivedObject without an explicit specification for which baseObject constructor to use.

In your definition of the derivedConstructor, then, you're going to need to specify exactly the baseObject constructor. Since I have no idea what your baseObject looks like, I've used a placeholder below:

derivedObject(const baseObject &base, const std::string &extra1)
    : baseObject(PARAM1, PARAM2)
{
    baseparameter1 = base.baseparameter1;
    baseparameter2 = base.baseparameter2;
    extraparameter1 = extra1;
}

In your particular case, if you're trying to create a derivedObject from a baseObject that already exists, you should define baseObject's copy constructor, and do as follows:

derivedObject(const baseObject &base, const std::string &extra1)
    : baseObject(base)
{
    baseparameter1 = base.baseparameter1;
    baseparameter2 = base.baseparameter2;
    extraparameter1 = extra1;
}

Upvotes: 2

Related Questions