Inheriting the assignment operator?

Discussion in 'General Programming Support' started by camelCase, Apr 14, 2012.

  1. camelCase The Case of the Mysterious Camel.

    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.
  2. s3rius Linux is only free if your time is worthless.

    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.
  3. camelCase The Case of the Mysterious Camel.

    Aw, damn =/
    Damned default assignment operators =/

    All right, thanks.

Share This Page