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

房东的猫 提交于 2019-11-29 08:25:21

问题


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.


回答1:


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.




回答2:


You can (and should) call the copy ctor of the base class, like:

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

Note that I turned the Base parameter into a Derived parameter, since only that is called a copy ctor. But maybe you didn't really wanted a copy ctor...



来源:https://stackoverflow.com/questions/9309577/how-to-declare-copy-constructor-in-derived-class-without-default-construcor-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!