Polymorphism and Slicing in C
When dealing with inheritance, C programmers may encounter the issue of slicing. Consider the following code:
#include <iostream> using namespace std; class Animal { public: virtual void makeSound() { cout << "rawr" << endl; } }; class Dog : public Animal { public: virtual void makeSound() { cout << "bark" << endl; } }; int main() { Animal animal; animal.makeSound(); Dog dog; dog.makeSound(); Animal badDog = Dog(); badDog.makeSound(); Animal* goodDog = new Dog(); goodDog->makeSound(); }
This code produces the following output:
rawr bark rawr bark
This may be surprising, as one might expect the output to be "rawr bark bark bark" instead. The difference lies in the use of slicing in the badDog assignment:
Animal badDog = Dog();
In this case, the Dog's data is sliced off into the Animal object, resulting in a loss of Dog-specific information. This is because Dog() creates a Dog object, but when assigning it to badDog, which is an Animal object, only the Animal part of the Dog is copied over.
To avoid slicing, one can use pointers or references:
Animal* badDogPtr = new Dog(); Animal& goodDogRef = dog;
Pointers and references behave as expected and allow for polymorphic behavior. This is because they refer to or hold a reference to the object, rather than having a copy of it like in the case of value semantics.
In languages like Java and C#, reference semantics are the default, while in C , value semantics are the default. For polymorphic behavior in C , explicit use of references or pointers is necessary.
The above is the detailed content of How Does Polymorphism and Slicing Affect Object Behavior in C ?. For more information, please follow other related articles on the PHP Chinese website!