Original from http://blog.csdn.net/dardgen/article/details/18790977
Virtual functions, pure virtual functions, virtual base classes, all of which are related to virtual, and these three definitions with medieval are confusing, so let's explain the difference between the three definitions:
1. Virtual functions are used in polymorphism to modify the parent class function to make sure that the parent class pointer is running the subclass function when it calls the child class object.
2. A pure virtual function is used to define an interface, that is, a pure virtual function is defined in the base class, and the base class does not have to be implemented so that subclasses can implement it.
3. Virtual base classes are used in multiple inheritance, and if the parent class inherits from the same parent class, only one parent class is instantiated (a bit of a detour, that is, just instantiate a grandfather's meaning =. =).
If the above does not understand does not matter, the following slowly explain clearly.
A. Virtual function
This is related to polymorphism, the definition of polymorphism is not clear to other places to understand first, polymorphism of the three necessary conditions: 1. Inherit 2. Overload 3. The parent class pointer points to the child class object.
Look at the program below:
The first is no use of virtual, not polymorphic:
[CPP] View plain copy class a { public: void printf () { cout<< "Printf a" <<endl; } }; class b : public a { public: void printf () { cout<< "Printf b" <<endl; } }; Int main (int argc, const char * argv[]) { a *a = new a (); a->printf (); b *b = new b (); b->printf (); return 0; }
Results:
printf A
printf B
This is the most basic usage, there is no polymorphism, only inheritance, the following is the use of polymorphic but no reference to the virtual keyword, polymorphic role refer to other places of the article:
[CPP] view plain copy int main (int argc, const char * argv[]) {A *a = new B (); A->printf (); return 0; }
Results:
printf A
Because the definition of a class is the same, so it is not written again, when the parent class pointer to the subclass object, if you do not use virtual, the parent class calls the method or call the parent's own method, do not invoke the method of subclass rewrite, so there is no implementation of the function of polymorphism, Let's try adding the virtual keyword to the parent class to see:
[CPP] View plain copy class a { public: virtual void printf () { cout<< "printf A "<<endl; } }; class b : public A { public: void printf () {