| Examles constants, pointers to constants, and constant pointers. | Lecture 2 - slide 9 : 42 Program 1 |
#include <iostream>
#include <string>
#include "point.h"
int main(){
Point p(1,2); // p is a Point
p.move(0,1);
const Point q(3,4); // q is a constant point.
q.move(1,2); // error (compile time)
const Point *r = &p; // r is pointer to constant point
r->move(1,2); // error (compile time)
Point *const s = &p; // s is a constant pointer to 'the point p'. *const is a 'declarator operator'.
s->move(1,2); // ok
s = NULL; // error: Assignment of read-only variable s. (Compile time)
Point const* w = &p; // w is a pointer to a constant point. const* is NOT a 'declarator operator'.
// Point const ... and const Point means the same.
const Point *w = &p; // Equivalent to the line above. But here w is illegally defined twice, of course.
w->move(1,2); // error (compile time). Cannot mutate a constant point.
const Point *const t= &p; // t is a constant pointer to a constant point.
t->move(1,2); // error (compile time)
t = NULL; // error (compile time)
Point const *const v= &p; // Same as definition of t.
}