Reputation: 1544
I want to convert a class to another class. I'm trying to use static_cas which almost always work for me, why doesn't it work in the following?
struct Mouse
{
Mouse() {}
// .......
};
struct Mice
{
Mice() {}
// .........
};
int main()
{
Mouse mouse;
Mice mice = static_cast<Mice>(mouse);
}
Upvotes: 2
Views: 4667
Reputation: 113242
Because not only is mouse
not an instance of Mice
, but it can't possibly be.
struct SomeBase
{
//...
};
struct SomeDerived : SomeBase
{
//...
};
struct Unrelated
{
//...
};
SomeBase * b;
SomeDerived * d;
Unrelated * r;
//....
b = static_cast<SomeBase *>(d); //allowed, safe
d = static_cast<SomeDerived *>(b); //allowed, unsafe
r = static_cast<Unrelated *>(d); //not allowed, what is it even meant to do?
Upvotes: 1
Reputation: 41331
You can only cast an instance of Mouse into Mice if Mice has a constructor accepting Mouse, or Mouse has an operator Mice
(latter is not particularly recommended).
Upvotes: 3