class myclass1 {
public:
virtual ~myclass1() {
}
};
class myclass2 : public myclass1 {
};
int main() {
myclass1 obj1;
myclass2 obj2;
myclass1 *p1 = &obj2;
myclass2 *p2 = static_cast<myclass2 *>(&obj1);
if( p1 && p2){
cout << typeid(p1).name() << endl;
cout << typeid(p2).name() << endl;
}
}
The output is as below:
P8myclass1
P8myclass2
Process finished with exit code 0
The code has two classes, I tried to use two types pointer to point to the other type. From base class to its children is totally ok while the other way around should not work ("myclass2 *p2 = static_cast<myclass2 *>(&obj1);"). If I use "dynamic_cast", the casted pointer will be null. But if I use "static_cast", the cast seems successful and the type is "myclass2" when I use typeid method.
When I am in debug mode in Clion, it seems the debugger knows the real type of the pointer, as shown in the image. It knows the type of p1 is "myclass2" and type of p2 is "myclass1". What is the magic of it?
obj1 = {myclass1}
obj2 = {myclass2}
p1 = {myclass2 * | 0x7ffeec114a08} 0x00007ffeec114a08
p2 = {myclass1 * | 0x7ffeec114a10} 0x00007ffeec114a10
question from:https://stackoverflow.com/questions/65947587/to-get-the-real-type-information-of-a-pointer-in-c