Skip to main content
Up and Coming
July 13, 2014

Inheritance and operator overloading

With the following piece of code:


#include<iostream>
using namespace std;

class base {
public:
base() {; }
base operator+(base ob2)
{
base temp;
return temp;
}
base operator=(base ob2)
{
cout << "Using base operator=() " << '\n';
return *this;
}
};

class derived : public base {
public:
derived() { ; }
derived operator=(base ob2)
{
cout << "Using derived operator=() " << '\n';
}
};

int main()
{
derived obj1, obj2, obj3;

obj3 = obj1 + obj2; // Uses derived operator=()

obj3 = obj1; // Uses base operator=()

return 0;
}



does anyone know why when the obj3 = obj1 + obj2 line is executed it uses the derived operator=() but when
obj3 = obj1 is executed it uses the base operator=() ?

Cheers.

EDIT: Not to worry, I worked it out in the end. :roll:
    This topic has been closed for replies.

    2 replies

    Participant
    July 16, 2014
    For those who did not work it out here is the answer:

    First of all one usually declares the assignment operator like this

    Base& operator=(const Base& ob2)


    But appart from that there is still the question how the assignment operators called?

    In the first case:

    obj3 = obj1 + obj2;


    Operator + operates on the base part of obj1 and obj2 returning a base object.
    Then we have derived = base which leads to the call of
    derived operator=(base)


    In the second case:

    obj3 = obj1; 


    c++ chooses the automatically generated assignment operator
    Derived::operator=(const Derived &);

    which then calls the provided assignment operator
    base operator=(base ob2);
    to copy the base part of
    the derived object.

    I could not solve the riddle at first because I forgot about the automatically generated assignment operators.
    medriftAuthor
    Up and Coming
    July 18, 2014
    "Knitschi" wrote:

    .... because I forgot about the automatically generated assignment operators.


    That's the part that got me stuck for a while. I could work out the first part but not second one. You live and learn. Thanks for confirming.