Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 651
unresolved_external Avatar asked Feb 16 '12 10:02

unresolved_external


People also ask

How do you write a derived class copy constructor?

class some_class { public : some_class(some_class const &instance_); // Copy-constructor some_class(some_class &instance_); // Default constructor }; When dealing with inheritance, be sure to invoke the base-copy-constructor, because otherwise, the base will not be affected.

Is copy constructor created by default?

Default Copy constructor: The compiler defines the default copy constructor. If the user defines no copy constructor, compiler supplies its constructor. User Defined constructor: The programmer defines the user-defined constructor.

Can a derived class have a constructor with default parameters?

A derived class cannot have a constructor with default parameters.

Is copy constructor created automatically?

No copy constructor is automatically generated.


1 Answers

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.

like image 133
Nawaz Avatar answered Nov 19 '22 22:11

Nawaz