Derived class object passed by value to function with base class parameter
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.
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.
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.
| Group: Object oriented |
| Language: C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax: OBJECT_SLICING |
| Impact: High |