top

hint for C++ Common Knowledge, item 8: pointers to pointers

The following examples are taken from one of Stephen's papers. Stephen kindly referred me to it when I just couldn't see why the pointer to pointer assignments in his book wouldn't compile. Harmless at first sight but devastating in its effect. (Probably an instance of blowing off ones leg - see Bjarne Stroustrup.)

pointer to pointer to const

from the book:
char* a[MAX];           // aka char**
const char** ppcc = a;  // compile error! why see below
rationale for the compile error:
const T ct;
T* pt;
const T** ppct = &pt;   // compile error
*ppct = &ct;
*pt = t_other;          // trash ct

pointer to pointer to base

from the book:
// D1 publicly inherits from B
D1 d1;
D1** ppd1 = &d1;
B** ppb = ppd1;         // compile error! why see below
rationale for the compile error:
// D1 and D2 inherit publicly from B
D1 d1;
D1* pd1 = &d1;
B** ppb1 = &pd1;        // compile error
D2* pd2;
B** ppb2 = &pb2;        // compile error
*ppb2 = *ppb1;          // pd2 now points to an D1-object
In Stephen's paper you will find not so obvious disguises of the above problems. If the compiler complains, don't even think about casting away the problem, he is right, as always, and you are wrong.