While playing with the virtual assignment operator implementation, I ended up with ridiculous behavior. This is not a compiler failure, since g ++ 4.1, 4.3, and VS 2005 have the same behavior.
In principle, the virtual operator = behaves differently than any other virtual function with respect to the code actually executed.
struct Base { virtual Base& f( Base const & ) { std::cout << "Base::f(Base const &)" << std::endl; return *this; } virtual Base& operator=( Base const & ) { std::cout << "Base::operator=(Base const &)" << std::endl; return *this; } }; struct Derived : public Base { virtual Base& f( Base const & ) { std::cout << "Derived::f(Base const &)" << std::endl; return *this; } virtual Base& operator=( Base const & ) { std::cout << "Derived::operator=( Base const & )" << std::endl; return *this; } }; int main() { Derived a, b; af( b );
The effect is that the virtual operator = has a different behavior than any other virtual function with the same signature ([0] compared to [1]), invoking the basic version of the operator when called through real derived objects ([1]) or Derived links ([3]), while it performs the function of a normal virtual function when called using basic links ([2]) or when the values โโlvalue or r are basic, and the other is a derived link ([4], [5 ]).
Is there any reasonable explanation for this odd behavior?
c ++ inheritance assignment-operator virtual-functions
David Rodrรญguez - dribeas Jun 09 '09 at 10:20 2009-06-09 10:20
source share