There is a compiler generated copy assignment, i.e. operator=(Derived &) in Derived , because Derived::operator=(Base const&) is not a copy destination for Derived . This prevents the compiler from generating a copy assignment if you use the assignment in your code.
So this line:
a = b;
calls the compiler class operator=(Derived &) for Derived , which then calls operator=(Base const&) . Therefore, Base called is printed.
Experiment: add this to the Derived class:
Derived & operator=(Derived const & obj) : Base(obj) { std::cout << "copy-assignment called" << std::endl; return *this; }
Now a=b will print:
The base is called
copy assignment is called
Also pay attention to the printing order.
Hope to clarify your doubts.
Now this,
a = static_cast<Base>(b);
functionally equivalent to this:
Base ___generated_tmp = static_cast<Base>(b); a = ___generated_tmp;
means a = ___generated_tmp calls operator=(Base const&) , since the type ___generated_tmp is equal to Base .
And the other two are pretty clear, as you already know.
Nawaz source share