Friday, April 04, 2014

Returning objects in C++

I recently discovered that returning an object in C++ might not be what you expect. I was surprised because in Java things would be different. Consider the following code:


getClassB() returns the mClassB attribute. Class B is as follows:


I wrote the following main function to test results:


I thought that a.getClassB().setVal(1) would set mClassB.mVal to 1. But when I read it using a.getClassB().mVal I got a meaningless number hinting that mVal was not set.

When I set the result of a.getClassB() to ClassB b and then set b.setVal(2) and read b.mVal I get 2 as expected.

Finally, when I use a.getClassBReference()->setVal(4) and then read it using a.getClassBReference()->mVal, I get 4.

I think that a.getClassB() returns a copy of mClassB which means that a setVal() operation on that copy does not modify a.mClassB.mVal. If you want to modify an field of an object attribute, the getter of that attribute has to return a reference, not a copy.