How to return pointer of a member and protect it.

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 :).
Make sure Vector is const-correct too:
1
2
3
4
5
6
7
8
9
10
class Vector { 
public:
  float getX() const { return x; };
private:
  float x = 0.0f;
  // ...
};

Vector position;
Vector const* getPosition() { return &position; }

http://coliru.stacked-crooked.com/a/c5d6dc9ea6f2754c

Consider making the member x publicly accessible.
Last edited on
Thank you for your reply.
But this is my code:

1
2
3
4
5
6
7
8
9
10
11
12
position.getX() is 
float getX();

	class Window {

		Vector position;

	public:

		const Vector *getPosition() const;

	};
Last edited on
Please post a small, self-contained, correct example of the code which exhibits the error.
[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

Hope this helps.
Last edited on
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

http://en.cppreference.com/w/cpp/language/pointer
Last edited on
Oops! Sorry!
It's not working. Which should I use? All I want is just a function which safely returns a value.
Last edited on
show your code, 'it's not working' is not enough information
Topic archived. No new replies allowed.