Re: Unexpected result with virtual operator= overload
On 8/1/2013 10:33 AM, ?? Tiib wrote:
On Thursday, 1 August 2013 15:34:31 UTC+3, Tobias M?ller wrote:
Lloyd <lloydkl.tech@gmail.com> wrote:
This is a small code piece I have written to test. It is overloading
"operator=". To my surprise this code prints "base" always! If I overload
"operator+" it prints "derived". Can you give a reason why "=" behaves
that way in this code?
#include <iostream>
using std::cout;
class derived;
class base
{
public:
virtual derived& operator=(const base& rhs);
This is a copy assignment operator for base.
The return type is unusual but it's a copy assignment operator
nevertheless.
Another thing that is unusual is that it is virtual. I have usually
reviewed such things as defects, since I can't imagine how that virtual
assignment should work.
If you actually assign to a derived object using a reference to base,
the *derived* assignment operator is called. Some could find it useful.
I know of no case that calls for it, but see no particular reason to
prohibit it.
};
class derived: public base
{
public:
derived& operator=(const base& rhs);
This is _not_ a copy assignment operator for derived, the parameter type
does not match.
Is not it also override of the virtual copy assignment operator of base class?
That's the intention, I believe.
This means that derived has a compiler-generated copy constructor, which
calls the copy assignment operator for all base classes and members.
Interesting, why the override copy assignment operator is not called?
The implicitly defined copy assignment op calls base classes' (and
members') assignment operators as if with the scope resolution, I think.
And when base:: is used, it circumvents the polymorphic call. That's
my take on it, anyway.
V
--
I do not respond to top-posted replies, please don't ask