ในส่วนนี้ เราจะพูดถึงข้อเท็จจริงที่น่าสนใจเกี่ยวกับคลาสเสมือนใน C++ เราจะเห็นสองกรณีก่อน แล้วเราจะวิเคราะห์ข้อเท็จจริงกัน
-
ขั้นแรกให้รันโปรแกรมโดยไม่ต้องใช้ฟังก์ชันเสมือนใดๆ
-
รันโปรแกรมโดยใช้ฟังก์ชันเสมือนใดๆ ภายใต้ฟังก์ชันที่ไม่ใช่เสมือน
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น -
#include <iostream>
using namespace std;
class BaseClass {
public:
void display(){
cout << "Print function from the base class" << endl;
}
void call_disp(){
cout << "Calling display() from derived" << endl;
this -> display();
}
};
class DerivedClass: public BaseClass {
public:
void display() {
cout << "Print function from the derived class" << endl;
}
void call_disp() {
cout << "Calling display() from derived" << endl ;
this -> display();
}
};
int main() {
BaseClass *bp = new DerivedClass;
bp->call_disp();
} ผลลัพธ์
Calling display() from base class Print function from the base class
จากผลลัพธ์ เราจะเข้าใจพฤติกรรมของ polymorphic ได้ แม้ว่าจะเรียกใช้ฟังก์ชันเสมือนภายในฟังก์ชันที่ไม่ใช่เสมือนก็ตาม ฟังก์ชันใดที่จะถูกเรียกใช้จะถูกตัดสินที่รันไทม์โดยใช้ vptr และ vtable
-
vtable − นี่คือตารางพอยน์เตอร์ฟังก์ชัน รักษาไว้ต่อคลาส
-
vptr − นี่คือตัวชี้ไปยัง vtable รักษาต่ออินสแตนซ์ของอ็อบเจ็กต์