Object slicing
Derived class object passed by value to function with base class parameter
Description
This defect occurs when you pass a derived class object by value to a function, but the function expects a base class object as parameter.
Risk
If you pass a derived class object by value to a function, you expect the derived class copy constructor to be called. If the function expects a base class object as parameter:
The base class copy constructor is called.
In the function body, the parameter is considered as a base class object.
In C++, virtual
methods of a class are resolved at run time
according to the actual type of the object. Because of object slicing, an incorrect
implementation of a virtual
method can be called. For instance,
the base class contains a virtual
method and the derived class
contains an implementation of that method. When you call the
virtual
method from the function body, the base class method
is called, even though you pass a derived class object to the function.
Fix
One possible fix is to pass the object by reference or pointer.
Passing by reference or pointer does not cause invocation of copy
constructors. If you do not want the object to be modified, use a const
qualifier
with your function parameter.
Another possible fix is to overload the function with another function that accepts the derived class object as parameter.
Examples
Result Information
Group: Object oriented |
Language: C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: OBJECT_SLICING |
Impact: High |
Version History
Introduced in R2015b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)