Forum Discussion
medrift
12 years agoHonored Guest
Inheritance and operator overloading
With the following piece of code:
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:
#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
- KnitschiHonored GuestFor those who did not work it out here is the answer:
First of all one usually declares the assignment operator like thisBase& 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 ofderived operator=(base)
In the second case:obj3 = obj1;
c++ chooses the automatically generated assignment operatorDerived::operator=(const Derived &);
which then calls the provided assignment operatorbase 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. - medriftHonored 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.
Quick Links
- Horizon Developer Support
- Quest User Forums
- Troubleshooting Forum for problems with a game or app
- Quest Support for problems with your device
Other Meta Support
Related Content
- 15 days ago
- 7 months ago
- 4 years ago