Alex Rivera | Logout

c++ const member function that returns a const pointer.. But what type of const is the returned pointer?

Asked 2010-10-08T07:26:34.813
51

I apologize if this has been asked, but how do I create a member function in c++ that returns a pointer in the following scenerios: 1. The returned pointer is constant, but the junk inside can be modified. 2. The junk inside is constant but the returned pointer can be modified. 3. Neither the junk, nor the pointer can be modified.

Is it like so:

  1. int *const func() const
  2. const int* func() const
  3. const int * const func() const

All of the tutorials I've read don't cover this distinction.

Side note: If my method is declared const then the tutorials say that I'm stating that I won't modify the parameters.. But this is not clear enough for me in the case when a parameter is a pointer. Do my parameters need to be like:

a. void func(const int* const x) const;
b. void func(const int* x) const;
c. void func(const int* const x) const;

Edit
Report

1 Answer

22

Some uses of const don't really make much sense.

Suppose you have the following function:

void myFunction (const int value);

The const tells the compiler that value must not change inside the function. This information does not have any value for the caller. It's up to the function itself to decide what to do with the value. For the caller, the following two function definitions behave exactly the same for him:

void myFunction (const int value);
void myFunction (int value);

Because value is passed by value, which means that the function gets a local copy anyway.

On the other hand, if the argument is a reference or a pointer, things become very different.

void myFunction (const MyClass &value);

This tells the caller that value is passed by reference (so behind the screens it's actually a pointer), but the caller promises not to change value. The same is true for pointers:

void myFunction (const MyClass *value);

We pass a pointer to MyClass (because of performance reasons), but the function promises not to change the value.

If we would write the following:

void myFunction (MyClass * const value);

Then we are back int he first situation. myFunction gets a pointer, which is passed by value, and which is const. Since MyFunction gets a copy of the pointer value, it doesn't matter for the caller whether it is const or not. The most important thing is that myFunction can change the contents of value, because the pointer variable itself is const, but the contents in it isn't.

The same is true for return values:

const double squareRoot(double d);

This doesn't make any sense. squareRoot returns a const double but since this is passed 'by value', and thus needs to be copied to my own local variable, I can do whatever I want with it.

answered 2010-10-08T07:44:38.370

Your Answer