There is a problem:
Is a parent class written with a virtual function? Can a sub-class overwrite its functions without the virtual function realize polymorphism?
The general answer is also polymorphism. Some people say that virtual modifiers are implicitly inherited. In this case, the virtual modifier is dispensable.
It is also said that when the parent class is used to go to the new subclass, the function without adding virtual will be faulty and should be added.
I wrote an example to verify whether there is a problem when virtual is not added:
[Cpp]
// TestPolymorphic. cpp: Defines the entry point for the console application.
//
# Include "stdafx. h"
# Include <iostream>
# Include <string>
Using namespace std;
Class Animal
{
Public:
Animal () {cout <"animal constructor" <endl ;}
Virtual ~ Animal () {cout <"animal destructor" <endl ;}
Virtual void cry () const {cout <"animal cry..." <endl ;}
};
Class Dog: public Animal
{
Public:
Dog () {cout <"dog constructor" <endl ;}
Virtual ~ Dog () {cout <"dog destructor" <endl ;}
Void cry () const {cout <"dog cry..." <endl ;}
};
Class Wolfhound: public Dog
{
Public:
Wolfhound () {cout <"Wolfhound constructor" <endl ;}
Virtual ~ Wolfhound () {cout <"Wolfhound destructor" <endl ;}
Void cry () const {cout <"Wolfhound cry..." <endl ;}
};
Int _ tmain (int argc, _ TCHAR * argv [])
{
Animal * pAnimal = new Wolfhound ();
Static_cast <Wolfhound *> (pAnimal)-> cry ();
Delete pAnimal;
Getchar ();
Return 0;
}
The result is printed as expected:
This shows that there is no problem without adding virtual.
Yesterday I reviewed Qian Neng's C ++ Programming Tutorial.
Www.2cto.com
It is always helpful to set all member functions as virtual functions as much as possible in a class.
The following are precautions for setting virtual functions:
1. Only member functions of a class can be declared as virtual functions.
2. static member functions cannot make virtual functions because they are not limited to an object.
3. inline functions cannot be used as virtual functions.
4. the constructor cannot be a virtual function.
As this weiqubo User told us, we should add pure ure to all the functions.
Author: lincyang