Temporary Variables: Keep Your Values Close, and Your References and Pointers Even Closer
As you know, in programming C++, it is much better to return a reference to an object than it is to return that object by value. As we will see in this article, it is also much better to pass a function parameter by reference than it is to pass it by value. But there are exceptions to this, as Jun Nakamura explains.
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”); } };
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().
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.