ตารางต่อไปนี้แสดงความแตกต่างระหว่าง Virtual Virtual Function และ Pure Virtual:
| ฟังก์ชันเสมือน | Pure Virtual Function |
|---|---|
| ฟังก์ชันเสมือนมีคำจำกัดความในคลาส | ฟังก์ชันเสมือนบริสุทธิ์ไม่มีคำจำกัดความ |
| การประกาศ:virtual funct_name(parameter_list) {. . . . .}; | การประกาศ:virtual funct_name(parameter_list)=0; |
| ไม่มีแนวคิดของคลาสที่ได้รับ | หากคลาสมีฟังก์ชันเสมือนบริสุทธิ์อย่างน้อยหนึ่งฟังก์ชัน คลาสนั้นจะประกาศเป็นนามธรรม |
| หากจำเป็น คลาสพื้นฐานสามารถแทนที่ฟังก์ชันเสมือนได้ | ในกรณีที่คลาสที่ได้รับมาของฟังก์ชันเสมือนล้วนต้องแทนที่ฟังก์ชันเสมือนแท้จริง |
ฟังก์ชันเสมือน
โค้ดตัวอย่าง
#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 of type B* pointing to d
b->s();// prints"D::s() called"
return 0;
} ผลลัพธ์
In Derived
ฟังก์ชันเสมือนบริสุทธิ์
โค้ดตัวอย่าง
#include<iostream>
using namespace std;
class B {
public:
virtual void s() = 0; // Pure Virtual Function
};
class D:public B {
public:
void s() {
cout << " Virtual Function in Derived class\n";
}
};
int main() {
B *b;
D dobj; // An object of class D
b = &dobj;// A pointer of type B* pointing to dobj
b->s();// prints"D::s() called"
} ผลลัพธ์
Virtual Function in Derived class