Search code examples
c++objectupcasting

Why can't I use objects created on stack for upcasting?


Is this an upcast or not? If not, please describe why. Thanks in advance.

C++ code:

Base base;
Derived derived;
base = derived; // is this the upcast? 

Solution

  • No, because you're not assigning a pointer or a reference, you're trying to assign an actual instance. That is, you're trying to copy the content of derived into the memory where base exists. What you'll end up with is slicing, only copying the contents of the Base part of derived.

    This should be covered in any decent C++ book.