Is it possible that void*
keep type-information?
I tried to make it forget the real types (B*
) by cast B* b
to void* v
, but it seems to know its origin.
It is good-luck for me, but I don't know why.
Here is a simplified code (full demo) :-
#include <iostream>
#include <memory>
using namespace std;
class B{public: int ib=1;};
class C:public B{public: int ic=2;};
int main() {
B* b=new C();
void* v=b; //<- now you forget it!
C* c=static_cast<C*>(v);
std::cout<<c->ib<<" "<<c->ic<<std::endl; //print 1 and 2 correct (it should not)
return 0;
}
I expected c
to point to the address of B*
(a wrong address), but it seems to know that v
is B*
and correctly cast.
Question
Why it work? Does void*
really remember the type?
How far can it "remember"?
Background
I am trying to create an void*
abstract class here, but surprised that it works.
I want to make sure that it is an expected standard behavior.
Edit: Sorry for the newbie question.
Now, I realize that I misunderstand about void*
.