ฟังก์ชันเสมือนใน C ++ ใช้เพื่อสร้างรายการพอยน์เตอร์คลาสพื้นฐานและเมธอดการเรียกของคลาสที่ได้รับใดๆ โดยที่ไม่รู้ด้วยซ้ำว่าคลาสอ็อบเจ็กต์ที่ได้รับมาเป็นอย่างไร ฟังก์ชันเสมือนได้รับการแก้ไขล่าช้า ณ รันไทม์
นี่คือการใช้งานฟังก์ชันเสมือนในโปรแกรม C++ -
ตัวอย่าง
#include <iostream>
using namespace std;
class B {
public:
virtual void s() { //virtual function
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
D d; // An object of class D
B *b= &d; // A pointer variable of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
} ผลลัพธ์
In Derived