Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does virtual assignment behave differently than other virtual functions of the same signature?
    text
    copied!<p>While playing with implementing a virtual assignment operator I have ended with a funny behavior. It is not a compiler glitch, since g++ 4.1, 4.3 and VS 2005 share the same behavior.</p> <p>Basically, the virtual operator= behaves differently than any other virtual function with respect to the code that is actually being executed.</p> <pre><code>struct Base { virtual Base&amp; f( Base const &amp; ) { std::cout &lt;&lt; "Base::f(Base const &amp;)" &lt;&lt; std::endl; return *this; } virtual Base&amp; operator=( Base const &amp; ) { std::cout &lt;&lt; "Base::operator=(Base const &amp;)" &lt;&lt; std::endl; return *this; } }; struct Derived : public Base { virtual Base&amp; f( Base const &amp; ) { std::cout &lt;&lt; "Derived::f(Base const &amp;)" &lt;&lt; std::endl; return *this; } virtual Base&amp; operator=( Base const &amp; ) { std::cout &lt;&lt; "Derived::operator=( Base const &amp; )" &lt;&lt; std::endl; return *this; } }; int main() { Derived a, b; a.f( b ); // [0] outputs: Derived::f(Base const &amp;) (expected result) a = b; // [1] outputs: Base::operator=(Base const &amp;) Base &amp; ba = a; Base &amp; bb = b; ba = bb; // [2] outputs: Derived::operator=(Base const &amp;) Derived &amp; da = a; Derived &amp; db = b; da = db; // [3] outputs: Base::operator=(Base const &amp;) ba = da; // [4] outputs: Derived::operator=(Base const &amp;) da = ba; // [5] outputs: Derived::operator=(Base const &amp;) } </code></pre> <p>The effect is that the virtual operator= has a different behavior than any other virtual function with the same signature ([0] compared to [1]), by calling the Base version of the operator when called through real Derived objects ([1]) or Derived references ([3]) while it does perform as a regular virtual function when called through Base references ([2]), or when either the lvalue or rvalue are Base references and the other a Derived reference ([4],[5]).</p> <p>Is there any sensible explanation to this odd behavior?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload