Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ double pointer cast

Tags:

c++

This code is invalid and does not compile:

struct A { int x; };

struct B : public A {};

void f( B** p ){
    A** pa = p; // type mismatch
}

It looks innocent though, and it appears to work with reinterpret_cast. I understand that there are cases where this wouldn't be so simple, e.g. when multiple inheritance is involved, but in this particular case here there shouldn't be any problem, and the compiler should be able to figure this out. So why is this not allowed in C++? And is reinterpret_cast a good way around this limitation, considering exactly the types given above?

like image 728
pentadecagon Avatar asked Jul 31 '26 18:07

pentadecagon


1 Answers

What might happen were it allowed:

struct A { int x; };

struct B : public A { int y; };

//...

B b;
B* pb = &b;
A** ppa = &pb;
A a;
*ppa = &a; // ppa points to pb, thus henceforth, pb == &a
pb->y = 100; // oops!
like image 91
ach Avatar answered Aug 03 '26 07:08

ach



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!