Search code examples
c++castingvisual-c++-2010-express

static_cast doubt


#include <iostream>
class A
{
public:
    A()
    {
        std::cout << "\n A_Constructor \t" << this <<std::endl;
    }
    void A_Method()
    {
        std::cout <<"\n A_Method \t" << this <<std::endl;
    }
};
class B:public A
{
public:
    B()
    {
        std::cout <<"\n B_Constructor \n";
    }
    void B_Method()
    {
        std::cout <<"\n B_Method \t" << this <<std::endl;
    }
};

int main()
{
    A *a_obj = new A;
    B *b_obj = static_cast<B*> (a_obj);  // This isn't safe.
    b_obj->B_Method();      
    getchar();
    return 0;
}

OUTPUT :

A_Constructor 001C4890
B_Method 001C4890

As no run-time check isn't involved in type conversion, static_cast isn't safe. But in this example, I got what I didn't even expect. Since there is no call to B::B(), any of it's members should not be able to get called by b_obj. Despite that I got the output.

In this simple case, I might have succeeded though it is known unsafe. My doubts are -

  • Though there is no call to B::B(), how was I able to access class B member functions.
  • Can some one please provide an example, where this is unsafe and might get wrong( though what I given before might serve as a bad example, but even better).

I did it on Visual Studio 2010 and with \Wall option set.


Solution

  • This is Undefined Behavior. Sometimes UB causes crashes. Sometimes it seems to "work". You are right that you shouldn't do this, even though in this case less bad things happened.