# C++ Object slicing **[Object slicing](https://en.wikipedia.org/wiki/Object_slicing)** occurs when a derived class object is copied into a base class object by value, silently discarding derived-class members. The code compiles and runs without error, but loses data and polymorphic behavior. Prevent slicing by passing polymorphic objects by reference or pointer, never by value. ## Example This example shows how slicing loses derived class data when passing by value. ```cpp // compile: g++ -o slicing slicing.cpp // run: ./slicing // description: demonstrate object slicing when copying derived to base #include class Animal { public: virtual ~Animal() = default; virtual void speak() { std::cout << "Animal sound\n"; } }; class Dog : public Animal { public: int tricks = 5; void speak() override { std::cout << "Woof! (" << tricks << " tricks)\n"; } }; void processAnimal(Animal a) { // passed by value: slicing occurs! a.speak(); } int main() { Dog dog; dog.tricks = 10; processAnimal(dog); // Dog sliced to Animal; tricks lost, prints "Animal sound" return 0; } ```