c++operator-overloadingabstract-base-class

Why default assignment operator is not called from assignment-from-base-class operator?


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?


Solution

  • If you want to force derived classes D to implement the function D::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:

    It's surprising, but a function that is declared pure can still provided with a definition.