Reputation: 27385
I've been experimenting with pointers and written the following code:
#include <iostream>
using std::cout;
struct A
{
int a;
char b;
A(){ a = 4; }
};
struct B
{
int c;
B(){ c = 5; }
};
A *a = new A;
B *b = new B;
int main()
{
a = (A*)b;
cout << a -> a; //5
}
Why B*
can be converted to A*
? Can any pointer be converted to any other pointer?
Upvotes: 1
Views: 136
Reputation: 1
"Can any pointer be converted to any other pointer?"
If you use a c-style cast like this, yes.
a = (A*)b;
The structure pointed to by b
will be just (re-)interpreted, just as it would be an A
. The correct c++ equivalent is
a = reinterpret_cast<A*>(b);
What you'll experience from such casts by means of consistency is unlikely to fit what's expected.
In other words: You'll experience all kinds of undefined behavior, accessing any members of a
after doing such cast.
You should use a static_cast<>
to let the compiler check, if those types are related, and can be casted somehow reasonably
a = static_cast<A*>(b);
Check these online samples to see the differences of static_cast<>
and reinterpret_cast<>
.
Upvotes: 1