kiriloff
kiriloff

Reputation: 26333

C++ forbidden pointer to pointer conversion

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 ?

Upvotes: 3

Views: 1109

Answers (1)

kiriloff
kiriloff

Reputation: 26333

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*.

Upvotes: 5

Related Questions