How do I return a pointer from a class and protect it from changing?
I tried with const Vector *getPosition() const; but when I try to use .getX(), an error comes out with the message "the object has type qualifiers that are not compatible with the member function".
So should I return a copy of that Vector or to do something else. Thanks :).
[edit] Oops! My brain worked backwards when answering this question. See mbozzi's post below. [/edit]
You want to return a pointer to a const object. For that the const must come after the asterisk.
1 2
// Return a (1) const-pointer to a (2) const value using a (3) const member function:
const Vector * const getPosition() const
You want to return a pointer to a const object. For that the const must come after the asterisk,
No - the const that modifies the referenced type comes before the star -- the top-level const (that modifies the pointer) comes after it.
1 2 3 4 5 6 7 8 9 10
// Return a (1) const-pointer to a (2) const value using a (3) const member function:
const Vector * const getPosition() const
Vector const * const getPosition() const
// Return a (1) non-const pointer to a (2) const value using a (3) const member function
const Vector * getPosition() const
Vector const * getPosition() const
// Return a (1) const pointer to a (2) non-const value using a (3) const member function
Vector * const getPosition() const