Search code examples
c++virtualcopy-constructorassignment-operatorobject-slicing

Slicing in inherited objects


The following cases point out the slicing problem: During an assignment: https://stackoverflow.com/a/274634/640639

During a function call: What is object slicing?

My question is wouldnt both of these cases be solved if the assignment operator and copy constructor are declared virtual and the derived class appropriately copies the required data? If so in principle pass-by-value should still work in these cases, correct?


Solution

  • Obviously, you cannot declare copy construction to be virtual: There is no object, yet. You can disable copy construction, though.

    That said, making assignment virtual still doesn't work because when slicing objects the static type of the assigned object is still just a base class. It will never become a derived class independent on what type you assign to it.