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.
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.
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.
A derived class cannot have a constructor with default parameters.
No copy constructor is automatically generated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With