乐闻世界logo
搜索文章和话题

What is object slicing in c++?

1个答案

1

Object slicing is a concept in object-oriented programming that occurs when a derived-class object is assigned to a base-class object, resulting in the loss of derived-class members (typically those exclusive to the derived class), leaving only the members present in the base class.

This phenomenon is typically caused by improper use of pointers or references. In C++, this commonly happens when a derived-class object is passed by value to a function expecting a base-class type. Since the function parameter is of base-class type, only the base-class members are copied, and derived-class-specific members are not copied.

Example:

Suppose we have the following two classes:

cpp
class Base { public: int base_var; }; class Derived : public Base { public: int derived_var; };

If we create a Derived object and assign it to a Base-type object, object slicing occurs:

cpp
Derived derivedObj; derivedObj.base_var = 1; derivedObj.derived_var = 2; Base baseObj = derivedObj; // Object slicing occurs here

In this example, when derivedObj is assigned to baseObj, derived_var is not copied to baseObj because baseObj, as a Base-type object, only contains members of the Base class.

How to Avoid Object Slicing?

To avoid object slicing, we typically pass objects via pointers or references, preserving the object's integrity, including its derived-class components:

cpp
Derived derivedObj; Base* basePtr = &derivedObj;

By using pointers or references, we can ensure access to derived-class members even within the base-class context. This approach avoids object slicing and correctly expresses polymorphic behavior.

2024年7月10日 11:50 回复

你的答案