Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 607
kiriloff Avatar asked Mar 08 '26 01:03

kiriloff


1 Answers

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

like image 119
kiriloff Avatar answered Mar 09 '26 13:03

kiriloff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!