i have my own class “SomeObject” with a few members.
now, i have another class “WorkingClass” containg this object as privat member.
My Question is: i want to create a Getter for the “SomeObject”, but i don’t want anyone to modify it.
which way is better, 1 or 2?
class WorkingClass
{
private:
SomeObject sObj;
public:
//... 1)
const SomeObject &const GetSomeObject()
{
return mousePosition;
}
//... 2)
const SomeObject *const GetSomeObject()
{
return &mouseMovement;
}
}
i know you can always cast away const, but still, i’m just trying to get my code clean and fail-safe
EDIT:
then i have a further question. when i have a smart-pointer member and use it a lot inside the class, and then suddenly want someone to have acces to read some values but nothing more, would this be a good solution or is that verbose again?
class X
{
private:
boost::shared_ptr<SomeObject> sob
public:
const const & GetSomeObject()
{
return *sob.get();
}
}
and how about returning a “const boost::shared_ptr<…> GetX()” ? it may not be really neccessary, but still not useless, as the compiler would forbid GetX().reset(..) in such a case, and without the const boost::… declaration this useless operation would be permitted. or am i wrong?
Neither is good:
const SomeObject &constis ill-formed. You cannot const-qualify a reference. (You can, of course, qualify the referent type.)const SomeObject *constis unnecessarily verbose. A function call expressiono.GetSomeObject()is an rvalue expression and only class-type rvalues can be const-qualified. You may as well just sayconst SomeObject*. (const SomeObject *constcan actually lead to issues with template instantiation, though such issues are rare.)As for whether you choose to return by pointer or by reference, it depends on how you are using the return value. Both can make sense in different circumstances. Regardless, you want to return a reference or pointer to a const object, not a const reference or a const pointer:
Usually, returning a reference is preferable.