Reputation: 1410
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;
}
Upvotes: 4
Views: 9329
Reputation: 5263
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;
}
Upvotes: 2
Reputation: 254581
If you just want to be able to get the value, then return by value. Also, declare the function const
. However, if it's large or expensive to copy, it might be better to return a const
reference so that the caller can choose not to make a copy of it.
If you also want to be able to modify it, then either return a reference (or a pointer if you like), or provide a "set" function. Alternatively, just make it public - there's not much point in pretending that it's encapsulated when it isn't.
If you do return a reference (or pointer), then make sure you have a const
overload, otherwise you won't be able to read the value from const
objects:
const unsigned int *Object::GetObjectIDPointer() const
{
return &objectID;
}
Upvotes: 1
Reputation: 1930
It depends on your method
GetObjectIDPointer()
if it is private method then use pointer, as it will make your member accessibility fast. but If the method is public you should always return a copy. As if you return a pointer it will breach basic principles of OOPS(Data hiding).
Upvotes: -1
Reputation: 726799
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.
Upvotes: 4