-
Returning a class
I have a class that needs to return a class (of the same type). (The real code is 400+ lines) Something like:
Code:
SampleClass SampleClass::Member(const SampleClass &c) const
{
SampleClass return_value;
/* Some code that figures return_value */
return return_value;
}
some_other_function()
{
SampleClass c, t = SampleClass(500), q;
c = t.Member(q);
// c != what it should
}
SampleClass has some dynamically allocated members, allocated in the constructor and deallocated in the destructor. However, whenever the function above is called, if I output the values in return_value immediately before the return statement, everything is fine. However, incorrect information is returned from the function.
This seemed to work fine, until I compiled under a Linux environment. (Windows seems to let you get away with more.)
The best my mind can figure is that return_value's destructor is called before the value is actually returned. (Since it's allocated on the stack.) The only way to avoid this that I can think of is to use pointers and dynamically allocate everything. Is there a Better Way?
-
You did not mention a copy constructor. Have your written an appropriate copy constructor?
-
Returning a class object from a function returns (in principle at least) a copy of the object being returned. Check the copy constructor of your class to ensure it works as intended. If the class has some dynamically allocated members, a rough rule of thumb is that it will require a hand-rolled copy constructor that dynamically allocates copies of the appropriate members rather than the copy constructor that the compiler gives you by default. For good measure, if you have to write a copy constructor, you may also wish to write an assignment operator (eg a member SomeClass &operator=(const SomeClass &)).
The reason you might get away with it for some compilers and not others is that returning a value from a class logically creates a temporary that is copied to the caller (hence the need for a working copy constructor). However, the C++ standard explicitly allows compilers some leeway: specifically, an acceptable optimisation is to avoid creating temporary if the only means of detecting that the temporary has existed is by manually tracking calls to constructors and destructor of the class. Not all compilers implement such an optimisation. The ones that don't will require the hand-rolled copy constructor in your case.
-
Sorry for the late reply. I read up on assignment operators, and that was my problem. The class works wonderfully now. (I did forget to mention I have a copy constructor - I'd been confusing it with the assignment operator. Now I understand their differences. (I have both now.))
Many Thanks!