Inheriting the assignment operator?

camelCase

The Case of the Mysterious Camel.
Reaction score
362
I was making some templates to partially simulate C# properties in C++ when I ran into the problem that I couldn't inherit the assignment operator, which is weird. So, I tried something trivial like:
Code:
class Base {
    public:
        virtual
        Base& operator= (int val) {
            i = val;
        }
        int i;
};

class Derived : public Base { };

int main () {
    Base    b;
    Derived d;
    b = 8;  //OK
    d = 7;  //Error: no operator "=" matches these operands
    return 0;
}
Needless to say, the above code doesn't work =/
I made the operator virtual because the inheriting class may want to override it.
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
The reason why this doesn't work is because Derived:: operator=() hides Base:: operator=() because their names are equal (damn smileys).

Code:
class Base {
    public:
        virtual
        Base& operator= (int val) {
            i = val;
        }
        int i;
};

class Derived : public Base { 
     Derived& operator= (Derived& other){ /* default-created assignment operator*/ }
};

D d;
d = xxx; //This always calls Derived::operator=(Derived& other)

Soo, in short Derived has to implement it's own assignment operator. Usually you just call the base's operator with it:

Code:
Derived& operator= (int val){
    Base::operator=(val);
    //Additional work, if necessary
}

A default assignment operator will attempt to call the base class' assignment operator if possible, but since you've overloaded it that doesn't work.
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
Aw, damn =/
Damned default assignment operators =/

All right, thanks.
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top