| constants/const-ptr-1.cc - Examles constants, pointers to constants, and constant pointers. | Lecture 2 - slide 28 : 29 Program 1 |
// Illustrates constness, in particular in relation to pointers. DOES NOT COMPILE.
#include <iostream>
#include <string>
#include "point.h"
int main(){
Point p(1,2); // p is a Point. It can be moved (by mutation).
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 a constant point
r->move(1,2); // ERROR (compile time)
Point const *rr = &p; // rr is pointer to a constant Point - fully equivalent to definition or r above.
Point *const s = &p; // s is a constant pointer to 'the point p'. *const is a 'declarator operator'.
s->move(1,2); // OK.
s = nullptr; // ERROR: Assignment of read-only variable s. (Compile time)
const Point *const t= &p; // t is a constant pointer to a constant point.
t->move(1,2); // ERROR (compile time)
t = nullptr; // ERROR (compile time)
Point const *const v= &p; // Same as definition of t (Point and const has just been reversed).
}