What happens when a derived object is passed by value to a function taking a base class parameter in C++?
Correct answer
C. The derived part is sliced off, leaving a base copy
18 views
C. The derived part is sliced off, leaving a base copy
18 views
Passing by value constructs a base object from the derived one using the base copy constructor, so only the base subobject is copied and the derived members, along with virtual dispatch, are lost. This is object slicing, and it is why polymorphic functions should take references or pointers. Containers of base objects show the same problem, so containers of pointers or smart pointers are used instead.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.