How to declare copy constructor in derived class, without default construcor in base?

unresolved_external picture unresolved_external · Feb 16, 2012 · Viewed 34.2k times · Source

Please take a look on the following example:

class Base
{
protected:
    int m_nValue;

public:
    Base(int nValue)
        : m_nValue(nValue)
    {
    }

    const char* GetName() { return "Base"; }
    int GetValue() { return m_nValue; }
};

class Derived: public Base
{
public:
    Derived(int nValue)
        : Base(nValue)
    {
    }
    Derived( const Base &d ){
        std::cout << "copy constructor\n";
    }

    const char* GetName() { return "Derived"; }
    int GetValueDoubled() { return m_nValue * 2; }
};

This code keeps throwing me an error that there are no default contructor for base class. When I declare it everything is ok. But when i dont, code does not work.

How can I declare a copy constructor in derived class without declaring default contructor in base class?

Thnaks.

Answer

Nawaz picture Nawaz · Feb 16, 2012

Call the copy-constructor (which is generated by the compiler) of the base:

Derived( const Derived &d ) : Base(d)
{            //^^^^^^^ change this to Derived. Your code is using Base
    std::cout << "copy constructor\n";
}

And ideally, you should call the compiler generated copy-constructor of the base. Don't think of calling the other constructor. I think that would be a bad idea.