0

Can someone please explain why the below code is able to call the SayHello function and print out "Hello".

The constructor and destructor never get called as there is no object actually created, so why then can I call the SayHello function??

class A
{
public:
    A()
    {
        std::cout<<"In Constructor"<<std::endl;
    };
    ~A()
    {
        std::cout<<"In Destructor"<<std::endl;
    };

    void SayHello()
    {
        std::cout<<"Hello"<<std::endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{       
    A* a = nullptr;
    a->SayHello();

    return 0;
}
Harry Boy
  • 4,159
  • 17
  • 71
  • 122

1 Answers1

3

This is undefined behaviour. It happens to work because SayHello doesn't access any member data. Don't do this.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193