Implementing a derived class from abstract base class with assignment operator by using dynamic cast in base-to-derived assignment operator, I'd like to call derived-to-derived assignment operator. This works.
#include <iostream>
using namespace std;
class base
{
public:
virtual base& operator = (const base& ) = 0;
};
class derived: public base
{
public:
derived (int d): data(d) {};
derived& operator = (const base& b)
{
if (&b == this) return *this;
const derived &d = dynamic_cast<const derived&> (b);
*this = d;
return *this;
}
derived& operator = (const derived& d)
{
if (&d == this) return *this;
data = d.data;
return *this;
}
private:
int data;
};
However when I do not implement derived& operator = (const derived& d) explicitly or use
derived& operator = (const derived& d) = default;
compilation fails, complaining 'undefined reference to base::operator=(base const&)' (i.e. trying to call abstract method). Why? Is there a way not to implement default assignment? This seems to be a redundant and may result in future errors, e.g. in case of adding a field into base/derived class without corresponding modifying the assignment operator?
If you want to force derived classes
Dto implement the functionD::operator=(const base&)and you also want them to be able to have their own defaulted copy-assignment operators,D::operator=(const D&) = default;, then:base::operator=(const base&)pure (as you have already done), andbase::operator=(const base&). This looks like:base& base::operator= (const base&) = default;The definition ofbase's copy-assignment operator is required since it will be called by the defaulted copy-assignment operator of each derived class.It's surprising, but a function that is declared pure can still provided with a definition.