I have a class member defined as:
someType* X;
and I get it like:
someType* getX() {return x;}
I would like to get the value rather than the pointer i.e.:
someType getX() {return x;} //this is wrong
what is the proper syntax for this? How do I get the value rather than the pointer?
someType getX() {return *x;}
Note though that this returns x
by value, i.e. it creates a copy of x
at each return*. So (depending on what someType
really is) you may prefer returning a reference instead:
someType& getX() {return *x;}
Returning by reference is advisable for non-primitive types where the cost of construction may be high, and implicit copying of objects may introduce subtle bugs.
*This may be optimized away in some cases by return value optimization, as @paul23 rightly points out below. However, the safe behaviour is not to count on this in general. If you don't ever want an extra copy to be created, make it clear in the code for both the compiler and human readers, by returning a reference (or pointer).
someType getX() const { return *x; }
or alternatively, if someType
is expensive to copy, return it by const
reference:
someType const &getX() const { return *x; }
Note that const
qualifier on the method.
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