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

  • As Henry Spencer said, "if you lie to the compiler, it will get its revenge." By performing your cast you forced compiler to believe you, and you got quite expected result. – Gene Bushuyev Jan 10 '11 at 17:55
  • Compiling this exactly as you have provided it, I get an error: cast.cpp:31:12: error: no member named 'check' in 'B' – user257111 Jan 10 '11 at 17:56
  • @Ninefingers - I was giving meaningful names while editing here, so that every one could easily follow. But forgot to change one. Thanks for pointing out. – Mahesh Jan 10 '11 at 17:58
up vote 4 down vote accepted

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.

  • I get sometimes confused by the word undefined behaviour. Whenever it is said, does it mean that defined behaviour is also subset of it. – Mahesh Jan 10 '11 at 17:54
  • @Mahesh: Yes. Undefined Behaviour means that anything might happen. Including your program appearing to operate correctly. Or nothing at all. Or your compiler vendor coming around and smacking you in the head with a baseball bat. All valid as far as the Standard is concerned. – Puppy Jan 10 '11 at 17:59
  • undefined behavior behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements. Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior... – Gene Bushuyev Jan 10 '11 at 18:01
  • Undefined Behavior means C++ can do anything it wants, and any results you don't like are your own fault. Sometimes what actually happens matches up with what some people "expect", partly by luck. The technical term for what I think you mean by "defined behavior" is "observable behavior"; and when a program contains UB, all promises about observable behavior are off. – aschepler Jan 10 '11 at 18:02

What you are trying is undefined behaviour so ANYTHING could happen. This seems to work (and probably works) fine as you don't try to access any data members (you don't have any). Try to add some data members to both classes and access it from methods, you will see that behaviour will change to completely unpredictable.

I doubt that this particular case is UB. First, it just casts a pointer from one type to another. Since there is no virtual/multiple inheritance involved, no pointer adjustment is performed, so basically the pointer value stays the same. Surely it points to an object of a wrong type, but who cares, as long as we don't access any B members, even if there were some? And even if there was pointer adjustment involved, it would still be okay if we didn't access any memory pointed by it, which we don't.

Then, the example calls a method of B. Since it is not virtual, it just a normal function call with the hidden argument this (think B::B_Method(this)). Now, this points to an object of a wrong type, but again, who cares? The only thing it does is print it, which is always a safe thing to do.

In fact, you can even call methods using a NULL pointer. It works as long as the method isn't virtual and doesn't try to access anything pointed by this. I once had a library used by many programs. This library had a singleton-like class which had to be constructed explicitly, but none of the programs actually did it. The instance pointer was initialized to NULL by default, as it was global. It worked perfectly since the class had no data members at all. Then I added some and all the programs suddenly started to crash. When I found out the reason, I had a really good laugh. I've been using an object that didn't even exist.

  • Decent explanation of why this will "work" on most compilers. But yes, UB: 9.3.1p1: If a nonstatic member function of a class X is called for an object that is not of type X, or of a type derived from X, the behavior is undefined. – aschepler Jan 10 '11 at 21:56
  • @aschepler, in general this is true because nobody knows what the function might do. But I can't imagine why this particular function wouldn't work on any imaginable compiler and hardware, not just on most compilers. This is like saying that passing an invalid pointer to a C function is UB, but it is not if that function just prints it or even ignores it completely. – Sergey Tachenov Jan 11 '11 at 7:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.