In C++, the method call will not check for the object creation. For example, consider the following class
Class Test
{
public:
int x;
void play(int y)
{
cout<<"X Value: "<<x<<endl;
cout<<"Y Value: "<<y<<endl;
}
}
int main ()
{
Test t = new Test();
t->x = 5;
t->play();
return 0;
}
In the above code, when I called the play method, internally the method is executed by sending the class instance as a method parameter like below.
void play(Test obj, int y)
If we call the play method without creating an object, it won't fail in the calling line. The c++ call the play method with null parameter (void play(null, 5)). So, the program throws an exception when the method is trying to use the class object to access its member(int x). (Note: If we didn't use any class members in the method, then the method is successfully executed even without creating the object for class).
Consider the below code:
Class Test
{
public:
void play(int y) { cout<<"Y Value: "<<y<<endl; }
}
int main ()
{
Test t;
t->play(5);
return 0;
}
In the above example, I called the Play method of Test class without creating the object for the class. Internally play method is called by using null parameter(void play(null, 5)). But, inside the class we didn't used the class object. So, it won't throw any exception and happily printed "Y Value: 5" string and the program will successfully got executed.
Like this, in your code, when you tried to call the play method it will call the method with null parameter. Since, your method is not used any class members your method will got executed successfully. The static_cast<> is not doing any magic here. static_cast<> is used only for the following purposes
- Converting a pointer of a base class to a pointer of a derived class
- Convert numeric data types such as enums to ints or ints to floats
In your code, static_cast will not convert the Base class to Test class. It just returned some junk pointer. If you used any class members in the play method definitely the call will get failed in the line where you tried to used the class object.