Posted Joe Chu cpp3 minutes read (About 518 words)0 visits
Object Slicing
Slicing in C++ and how to prevent it.
Introduction
In C++, when a derived class object is assigned to a base class object, the fields and methods in the derived class object will be sliced off. Since these extra components are not used, the priority is given to base class. The following example shows how slicing happens.
classDerived : public Base { public: Derived() { std::cout << "Derived() called\n"; } voidgetName()constoverride{ std::cout << "Derived getName()\n"; } };
intmain(){ Derived d; Base& b = d; b.getName(); return0; }
1 2 3
Base() called Derived() called Derived getName()
Note that std::vector<Base&> vec; is not legal. Containers like std::vector manage memory for their elements, and they assume ownership of the objects stored in them. Objects stored in a container need to be owned by the container to ensure proper memory management. References, on the other hand, do not own the objects they refer to. They are just aliases or alternative names for existing objects. Allowing a container to hold references could lead to dangling references if the original objects are destroyed while the container still holds references to them.
Use Pointers
A better way to prevent object slicing is to use pointers.