Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer - Examining possible dangers
(Page 5 of 6 )
By now I’d expect you don’t want to pass function arguments by value anymore unless they are primitive values. In case you are still hesitating, let's look at how passing by value can create a problem named ‘object slicing’. Then if you are convinced that const references are your salvation, stay alert, because there are situations where they perform as poorly as objects that are passed by value.
Things are never easy, you just have to make sure you know what you are doing… all the time.
Object Slicing.
Slice.
[slīs]
A thin broad piece cut from a larger object.
One of the dangers of passing an object by value is that the object might be sliced when the function accepts the object's baseclass by value. The compiler will create an instance of that baseclass instead of a copy of the derived class, and now you could be in a lot of trouble, because any virtual behavior that was implemented in the derived class is lost.
Here is a quick example:
class Base {
public:
virtual ~Base() {}
virtual void foo() const {
(void)printf(“Base::foo() called.\n”);
}
};
class Derived {
public:
void foo() const {
(void)printf(“Derived::foo() called.\n”);
}
};
It is easy to see which foo() is being called, and we can now add the following functions and code to see how this slicing works:
void CallByValue(Base obj) { obj.foo(); }
void CallByReference(Base const &obj) { obj.foo(); }
/* test code */
(void)printf(“Slicing test.\n”);
Derived derived_obj;
(void)printf(“Calling CallByValue: “);
CallByValue(derived_obj);
(void)printf(“Calling CallByReference: “);
CallByReference(derived_obj);
The result confirms the description: “passing a derived object to a function that takes it baseclass as its parameter, causes this object to be sliced”… The first function call used Base::foo() and the second Derived::foo().
Slicing test.
Calling CallByValue: Base::foo() called.
Calling CallByReference: Derived::foo() called.
When passed by reference, the object remains intact. The function CallByReference doesn’t need a temporary object; it works with a reference to the baseclass instead of the object passed in.
Unfortunately we cannot blindly construct a coding rule that passing a function argument by const reference is always better than passing it by value. The reason for this is the fact that const references allow the compiler to perform an implicit conversion. We have actually come full circle.
Next: The cost of implicit conversion >>
More C++ Articles
More By J. Nakamura