2

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);
}
user1086635
  • 1,536
  • 2
  • 15
  • 21
  • 5
    Just because "mice" is plural of "mouse" it does not mean these classes are related. There is no conversion that allows converting a mouse into mice - it would be magic, really... – lapk Dec 09 '11 at 23:24
  • 1
    You basically need to understand what `static_cast` does. See a short description of how it works [here](http://stackoverflow.com/questions/332030/when-should-static-cast-dynamic-cast-and-reinterpret-cast-be-used). – Jon Dec 09 '11 at 23:27

2 Answers2

3

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).

UncleBens
  • 40,819
  • 6
  • 57
  • 90
1

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?
UncleBens
  • 40,819
  • 6
  • 57
  • 90
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251