I have what is hopefully a simple question here. For my member variables of my classes, all of which are private, should I use accessors to return a pointer or return the variable itself? Or should I be doing something else?
Example:
unsigned int *Object::GetObjectIDPointer()
{
return &objectID;
}
OR
unsigned int Object::GetObjectID()
{
return objectID;
}
This depends a lot on what you would like to do with them: if you plan the users of your class to be able to modify variables inside your class (a terrible and strongly discouraged thing) you can return pointers or references; otherwise, return the variable itself.
There is an exception to this rule when objects that you'd like to return are large, such as vectors, sets, maps, etc. If you decide to make accessors to them, you should return them by constant reference.
I would say, take the second solution.
More generally, you can return a copy of the object itself, the compiler is likely to optimize out any unnecessary copies with the copy elision optimization.
You can also return a const reference to the field:
const MyType& getMyField() const { return this->myField; }
That way, no copies are created and the value can't be modified (except with const_cast
).
But for an int, I think you should return a copy, as in your second solution:
unsigned int Object::GetObjectIDPointer()
{
return objectID;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With