In C++, why can a pointer assigned nullptr call member functions? I expected that the function will get an error when it is called since the pointer does not point the region of memory generated the instance of class.
The code I tried is as below:
#include <iostream>
class Foo
{
public:
int var = 10;
void func();
};
void Foo::func() {
std::cout << "func() function called." << std::endl;
}
int main(int argc, char const* argv[])
{
Foo foo;
Foo* foo_ptr = (Foo*) nullptr;
// std::cout << foo_ptr->var << std::endl; // segmentation fault
foo_ptr->func(); // Output: "func() function called." WHY??
foo_ptr = &foo;
std::cout << foo_ptr->var << std::endl; // Output: 10
foo_ptr->func(); // Output: "func() function called."
return 0;
}
Output:
$ g++ -O0 -Wall callSample.cpp && ./a.out
callSample.cpp:6:13: warning: in-class initialization of non-static data member is a C++11 extension [-Wc++11-extensions]
int var = 10;
^
1 warning generated.
func() function called.
10
func() function called.
Environment:
$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/c++/4.2.1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin