Forum Discussion

🚨 This forum is archived and read-only. To submit a forum post, please visit our new Developer Forum. 🚨
medrift's avatar
medrift
Honored Guest
12 years ago

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:

2 Replies

Replies have been turned off for this discussion
  • 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.
  • medrift's avatar
    medrift
    Honored Guest
    "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.