OOP polymorphism
In OOP languages, a Base-class object pointer can do function call according to the actual type of the object. Let's see a example in Java.
Public classanimal{ Public voidSpark () {System.out.println ("Spark"); } } Public classDogextendsanimal{ Public voidSpark () {System.out.println ("Wangwang"); }} Public classCatextendsanimal{ Public voidSpark () {System.out.println ("Miaomiao"); }} Public classmain{ Public Static voidMain (string[] args) {animal[] animals=NewAnimal[3]; animals[0]=NewDog (); animals[1]=NewCat (); animals[2]=NewAnimal (); for(Animal it:animals) {It.spark () }}}
It would output
Wangwangmiaomiaospart
That ' s " polymorphism ".
c++virtual function
Above codes is very natual for Java programmers. However in C + +, you can ' t get such "polymorphism" without the "virtual" keyword decorating the functions. Without "virtual", C + + would output
Sparksparkspark
Take a look at <the virtual table> If you don ' t yet know about virtual table. This article explains why "virtual" came out, and how virtual function was supported by virtual table.
Why virtual table
Why does C + + use virtual table?
=>because C + + compiler does not know the actual function address
--->why?
=>because C + + compiler does not know the exact type (Cat? Dog? Animal?) Of the Oject the pointer "Panimal" points to
---why? is, any of the compiler can figure out the object type?
=>yes! Using "Object type Tracking"!
Object Type Tracking
Let's consider the sources where an object is pointer gets its value. 2 sources indeed.
1. Another pointer2. Address of class instance
Where does "another pointer" get its value? Eventually, there's a pointer that gets the value from "class instance".
So, via tracking the assignment thread backwards to the original source object
= = The compiler is able the exact type of a pointer.
=>the compiler knows the address of the exact function being called
=>no virtual table is needed.
Object type tracking saves both virtual table memery and virtual table pointer of each class instances.
Where does object type tracking not work
Library linking.
If A library function returns a base-class pointer, there's no-for-the-compiler-track-to-the-original source O Bject.
Is virtual function table really necessary for C + +