Transferred from: http://www.cnblogs.com/smhy8187/articles/1686815.html
The use of virtual functions is in the parent class in the same class, but it is easy to change or unclear features extracted, as subclasses need to re-implement the operation (override), we can call it "hot". and the virtual function is one of the keys to realize polymorphism in OOP .
Example (C #):
classBird { Public stringWing//Wings Public stringFeather//Feather...//other properties and behaviors Public Virtual BOOLFly ()//using the keyword virtual to define as a dummy function, this is a hotspot { //empty to let the subclass to achieve }} classSparrow: Bird//sparrows inherit from the birds.{...//define the properties and behaviors peculiar to the sparrow itself Public Override BOOLFly ()//Use the keyword override to reload the fly, to achieve your own flight{...//to achieve the sparrow's flying action }} classCrane: Bird//the cranes inherit from the birds.{...//define the unique properties and behavior of the crane itself Public Override BOOLFly ()//using the keyword override overload to make the crane fly{...//to realize the movement of the crane }}
So we just need to define the fly () in the abstract model "bird", which means that all subclasses derived from this "bird" will have the fly () , and the fly () is exactly how it is done, Then the specific subclass to achieve the better, will not affect the "bird" this abstract model.
For example, now we're going to do a bird shooter training system, so we can use the classes defined above:
//How to use virtual functions is also an example of polymorphism here.//define a method for shooting birds//notice here that a "bird" class is passed as a parameter, not a specific "bird". The good thing is, no matter what happens .//species of birds, as long as they inherit from the birds, do not miss:) (polymorphic way)voidshootbird (bird bird) {//when the birds are flying, they start shooting . if(bird. Fly ()) {...//Shooting Action }} Static voidMain () {/ /playing Sparrow Shootbird (NewSparrow ()); //Playing CraneShootbird (Newcranes ()); //is the process of beating birds, I just have to achieve a specific bird (from "bird" derived from) the definition, it can be//To shoot without modifying the Shootbird function and the bird base classShootbird (Newother birds ()); }
C # Virtual functions