Here, you will see an obsessive coding lover sharing interesting programming problems and skills.
virtual function的原理
[目的]
一般的function call都是compile time就決定好跳轉到哪一個code section address
但c++能透過把"virtual"關鍵字加到function前面,就會轉換成在runtime,依照實際上被創造的物件中的vtable中的function pointer,動態地選擇要跳轉到那一個code section address。
講起來有點繞口,簡化版就是說,runtime時不同的object(base class object或derived class object),內含的function table(儲存function的address)中的欄位值不同,因此會跳到不同的code section address去執行。
[原理]
virtual關鍵字,使得跳到"哪一個code section address",不再在compile time決定,而是在runtime決定。
呼叫function時,會去查看object的VTALBLE中的值,來查明該跳到哪一個function。
由於是runtime,所以叫做 "Late binding" or "dynamic binding")
https://openhome.cc/Gossip/CppGossip/VirtualFunction.html
[深入解析]
compiler看到有virtual關鍵字的class時,會在class中多加兩個data member, V-PTR & V-Table
V-ptr : pointer,指向V-Table
V-Table : 存有function所在位置.
V-Table的欄位要指向哪個function,端看你有沒有自定function, 沒有就指向father的function
http://ublearning.blogspot.tw/p/virtual-function.html