Reputation: 2061
I'm learning about c++ typecasting. I have this piece of code
class Y
{
private:
int m_y;
};
class X
{
public:
operator Y() { return Y(); }
private:
int m_x;
};
int _tmain(int argc, _TCHAR* argv[])
{
X x;
Y y;
y = static_cast<Y>(x); // calls the user defined conversion operator
Y* yPtr;
yPtr = static_cast<Y*>(&x); // error C2440: 'static_cast' : cannot convert from 'X *' to 'Y *'.
// Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
}
Why doesn't C++ return a pointer to an object of Y converted from the object x using the user defined conversion operator?
Upvotes: 2
Views: 537
Reputation: 238461
statc_cast
ing the object works because you create a temporary of the object using the converting constructor.
But when you static_cast
a pointer, you're making a temporary copy of the pointer. Pointers don't have converting constructors.
You cannot static_cast
unrelated pointers to another. Not even if they have converting constructors.
Even if it were allowed, consider what would happen if it worked like static_casting the object: A temporary would be created using the converting constructor, but instead of assigning the temporary to a variable, you'd be assigning the address of the temporary to a pointer. But since the temporary does not exist after the expression, the pointer would immediately be pointing to invalid memory.
Upvotes: 1
Reputation: 65770
Although an object of a given type can be converted to another type, you can't necessarily cast their pointers.
Converting an X
to a Y
in this example says "take this X
and make me a Y
from it". An X
is not a Y
, but it can be converted to one.
Converting an X*
to a Y*
says "this is a pointer to X
and now I'm saying it's a pointer to Y
". That doesn't make sense, because an X
is not a Y
, so you can't treat it like one until you convert the object.
Upvotes: 1