3

In C++, Type ** to Type const ** conversion is forbidden. Also, conversion from derived ** to Base ** is not allowed.

Why are these conversions wtong ? Are there other examples where pointer to pointer conversion cannot happen ?

Is there a way to work around: how to convert a pointer to pointer to a non-const object of type Type to a pointer to pointer to const object of type Type, since Type ** --> Type const ** does not make it ?

kiriloff
  • 25,609
  • 37
  • 148
  • 229
  • 1
    Why *should* it be allowed? You cannot in general convert a `U*` to a `W*`, because that makes no sense... – Kerrek SB Apr 21 '13 at 12:06
  • possible duplicate of [Why is it not OK to pass \`char \*\*\` to a function that takes a \`const char \*\*\` in C?](http://stackoverflow.com/questions/3496000/why-is-it-not-ok-to-pass-char-to-a-function-that-takes-a-const-char-in) – Bo Persson Apr 21 '13 at 13:38
  • i wanted to draw parallel between two conversion bans, which is not the point of the thread you mentionned. WIM, I am asking what other conversion bans are alike. – kiriloff Apr 21 '13 at 15:51
  • Duplicate Q is in C, not C++. But C++ has only tightened the type system rules, so the ban still stands for the same reason. – MSalters Apr 22 '13 at 10:57

1 Answers1

5

Type * to const Type* is allowed:

Type t;
Type *p = &t;
const Type*q = p;

*p can be modified through p but not through q.

If Type ** to const Type** conversion were allowed, we may have

const Type t_const;

Type* p;
Type** ptrtop = &p;

const Type** constp = ptrtop ; // this is not allowed
*constp = t_const; // then p points to t_const, right ?

p->mutate(); // with mutate a mutator, 
// that can be called on pointer to non-const p

The last line may alter const t_const !

For the derived ** to Base ** conversion, problem occurs when Derived1 and Derived2 types derive from same Base. Then,

Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;

Derived2 d2;
Derived2* ptrtod2 = &d2;

Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase  = ptrtod2 ;

and a Derived1 * points to a Derived2.

Right way to make a Type ** a pointer to pointer to a const is to make it a Type const* const*.

kiriloff
  • 25,609
  • 37
  • 148
  • 229
  • 1
    The variable names are unfortunately really unreadable. Simply replacing `ptrto` by `p` should actually help. – Konrad Rudolph Apr 21 '13 at 12:17
  • Wouldn't `*ptrtoptrtobase = ptrtod2 ;` cause slicing anyway? (I dont't know if assigning with pointers to the parent class produces slicing) – jdehesa Aug 18 '17 at 09:58