Principle C ++ member function with virtual functions

Consider the following two pieces of code:

#include <iostream>
class A {
public:
	void fun(){
		printf("Hello world\n");
	}
};
int main()
{
	A* a = nullptr;
	a->fun();
	return 0;
}
#include <iostream>
class A {
public:
	virtual void fun(){
		printf("Hello world\n");
	}
};
int main()
{
	A* a = nullptr;
	a->fun();
	return 0;
}

A first output "Hello world", the second error period.

Because:

When c ++ member function, the default of a member function in the first parameter address-based class, so more than the equivalent of fun (nullptr).

And when implementing virtual functions, it is the need for memory-related objects. When the virtual function call occurs, first of all in the first address to find this object virtual function table, find the corresponding virtual function will be called. The null pointer is not naturally a virtual function table.

He published 187 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105011378