C ++ Accessors - should I return a pointer to a member variable or an actual member variable?

In my opinion, I have a simple question. For my member variables of my classes, all of which are private, should accessors be used to return a pointer or return a variable itself? Or should I do something else?

Example:

unsigned int *Object::GetObjectIDPointer() { return &objectID; } 

OR

 unsigned int Object::GetObjectID() { return objectID; } 
+4
source share
4 answers

It depends on what you would like to do with them: if you plan on users of your class to be able to change the variables inside your class (a terrible and very discouraged thing), you can return pointers or links; otherwise return the variable.

There is an exception to this rule when the objects you want to return are large, such as vectors, sets, maps, etc. If you decide to access them, you must return them using the permalink.

+4
source

I would say take the second solution.
More generally, you can return a copy of the object itself, the compiler is likely to optimize any unnecessary copies by optimizing the elimination of copies .

You can also return the const link in the field:

 const MyType& getMyField() const { return this->myField; } 

Thus, copies are not created, and the value cannot be changed (except for const_cast ).

But for int, I think you should return a copy, as in your second solution:

 unsigned int Object::GetObjectIDPointer() { return objectID; } 
+2
source

If you just want to get the value, return it by value. Also declare a const function. However, if this is a large or expensive copy, it might be better to return a const link so that the caller can choose not to make a copy of it.

If you also want to change it, either return the link (or the pointer, if you want), or provide the "set" function. Alternatively, just make it public - there’s not much point in pretending to be encapsulated when it’s not.

If you return a link (or pointer), make sure you have a const overload, otherwise you cannot read the value from const objects:

 const unsigned int *Object::GetObjectIDPointer() const { return &objectID; } 
+1
source

It depends on your method.

 GetObjectIDPointer() 

if this is a private method, then use a pointer, as it will quickly make your member available. but if this method is public, you should always return a copy. As if you are returning a pointer, this violates the basic principles of OOPS (data hiding).

-1
source

All Articles