The questions are:
a) Is the following code legal or not ? (considering it crashes at run-time)
b) If there is any compiler flag for gcc or MVC to show at compile time, a potential problem in the following code ?
#include <iostream>
using namespace std;
class A
{
public:
void write(){ cout<<"A"; }
};
class B
{
public:
virtual void write(){ cout<<"B"; }
};
int main()
{
A *pa=(A*) new B();
pa->write();
B *pb=(B*) new A() ;
pb->write();
delete pa;
delete pb;
return 0;
}
Thanks!
No, it’s not legal.
Bdoesn’t derive fromA, nor vice versa. Forcing a cast like this results in undefined behaviour. You’re telling the compiler “shut up, I know what I’m doing”, which leads to all sorts of trouble. This is one reason to avoid old C-style casts, and use C++-style casts instead (static_cast, etc.).