"Is this a safe operation?"
No. C-style casting in C++ is not generally considered as safe operation. Reason? There is a lots of different kinds of casts and using C-style cast means you tell the compiler that it should select one of them. Problem is that this might lead to different result than you wanted. One chapter in "C++ Coding Standards : Rules, Guidelines, and Best Practices" is about that.
Example imagine this:
class Based { ... }
class Derived : Based { ... }
and now source file #1:
class Based;
class Derived;
Derived* boo();
Based* foo1()
{
Derived *a = boo();
Based *b = (Based*)a;
return b;
}
source #2:
#include "Based.h" // Contains definition of Based class
#include "Derived.h" // Contains definition of Derived class
Derived* boo();
Based* foo2()
{
Derived *a = boo();
Based *b = (Based*)a;
return b;
}
Both sources will compile! But foo1()
uses different kind of cast then foo2()
! First case is bad and will work only in exceptional cases (but even this is not defined by standard).
In other words, in foo1()
you tell the compiler "treat pointer of Derived
as if it would be pointer of Based
", but in the second case you tell the compiler "cast Derived
to it's parent, Based
".
foo1()
might randomly crash or lead into very weird behavior of your code.
And btw. your compiler will probably never warn you about that. So, avoid C-style casting!