2
#include <iostream>
using namespace std;
class A
{
public :
    void show()
    {
        cout << "A "  << endl;
    }

};
class B : public A
{
public :
    void show()
    {
        cout << "B "  << endl;
    }
};
int main()
{
    A *a =NULL;
    a->show(); // Prints 'A'
    B *b =NULL;
    b->show(); // Prints 'B'
}

How is this getting printed and when we inherit show from A to B, how can show() be called using a B class object? What exactly happens when inherited A from B?

Niall
  • 30,036
  • 10
  • 99
  • 142
  • 4
    De-referencing a null pointer is undefined behavior. What compiler are you using that allowed such behavior? – Cory Kramer Sep 26 '14 at 12:08
  • 1
    I've just tried his code with g++ 4.8.1 and it prints A and B too. – Igor Popov Sep 26 '14 at 12:10
  • 3
    Well, it´s still UB. The compiler etc. can do whatever they want. And as soon there is something virtual, it will break for sure. – deviantfan Sep 26 '14 at 12:11
  • 2
    It's undefined behaviour. But to take a guess at why this happens; the "invisible" parameter for `this` passed to member functions is NULL, but it is never itself referenced, so the code "looks" to work, but it is really undefined behaviour. Anything could happen. – Niall Sep 26 '14 at 12:13
  • 1
    This is indeed undefined behavior but it is common practice not to check "this" parameter in non-virtual method call until data members are accessed. For instance in Microsoft standard library there is [GetSafeHwnd](http://msdn.microsoft.com/en-us/library/d64ehwhz.aspx) method that explicitly: "Returns m_hWnd, or NULL if the this pointer is NULL." – dewaffled Sep 26 '14 at 12:23
  • This has been asked before – crashmstr Sep 26 '14 at 12:50
  • @crashmstr wheres the link to the dup – Brandin Sep 26 '14 at 12:50

1 Answers1

1

It's undefined behavior, but a lot of implementations would behave the way you're seeing. Consider this call:

a->show();

The compiler can see that A has no base class, and show() is not virtual. So the only possible function to invoke is A::show(). So great, invoke it! All you need to do (if you're the compiler) is pass a as this, i.e. the hidden first argument to the function. And if this is never used in the function, it's likely to work just fine.

Even so, this is not guaranteed to work, is non-portable, and is a bad idea. Don't do it. Your trousers might burn.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436