Reputation: 34036
I am trying to teach some students that in the following case you should pass by reference, otherwise the objects will be copied.
note: They don't know about copy-constructors yet, so if possible I would not like to mention them in the example.
int sumOfSizes(CObject const & a, CObject const & b)
{
return a.getSize() + b.getSize();
}
Can anybody help me with a real-world example where the sum is infact not what is expected?
Upvotes: 3
Views: 145
Reputation: 272657
As @Space_C0wb0y implied in his comment, the only way this could do something "unexpected" when passing by value is if the copy constructor for CObject
did something "unexpected" (such that the local CObject
instances were not equivalent (in whatever sense) to the original instances). This in turn would indicate bad design.
Therefore, your counterexample will have to rely on a contrived, badly-designed CObject
.
Upvotes: 6