Search code examples
c++c++11visual-studio-2013nullptr

How is possible that accessing nullptr works?


I have a simple class:

class B
{
public:
    int getData() { return 3; }
};

then, I initialize a pointer to it with nullptr:

B *foo{ nullptr };

And then, trying to use it comes the surprise:

int t = foo->getData();

and t is now 3. How is that possible without constructing the class? Is it because getData() does not use "this"? That broke all my knowledge about pointers.

Is that expected behavior? I am working in Visual Studio 2013.


Solution

  • Is that expected behavior?

    No, it's UB, anything is possible.

    Is it because getData() does not use "this"?

    Yes, it might work because this won't be used in the special case, but nothing is guaranteed.