1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

class sample {
int n;
public:
void set( int i )
{ n = i; }
// Changing n is intended
int get() const
{ return n }
// Cannot (does not) change n }

returning const

You can indicate that the return value is in some sense constant:

const int n = 1; //hereafter n is constant int const v() { return n; }
const int w() { return n; }
const int* x() { return &n; }
int* const y() { return &n; }
// error return of non-const*
// pointer from const*

const int* const z() { return &n; }

int main() {
int i = 1;
const int* q = &i;
int* s;

// pointer to const // pointer

i = v(); // okay
i = w(); // okay
q = x(); // okay
s = x(); // error
// assignment of non-const*pointer from const* q = y(); // okay
s = y(); // okay
q = z(); // okay
s = z(); // error
// assignment of non-const* pointer from const*

}

22-Mar-98

Page 12

C201/TAM