Khi hàm ảo được gọi từ hàm không ảo (non-virtual) của cùng class, hành vi đa hình (polymorphism) vẫn hoạt động bình thường nhờ cơ chế vtable/vptr.
Ví dụ
#include <iostream>
using namespace std;
class BaseClass {
public:
void display() { cout << "Base display\n"; }
void call_disp() {
cout << "Calling display from base\n";
this->display(); // gọi ảo qua this
}
};
class DerivedClass : public BaseClass {
public:
void display() { cout << "Derived display\n"; }
void call_disp() {
cout << "Calling display from derived\n";
this->display();
}
};
int main() {
BaseClass* bp = new DerivedClass;
bp->call_disp(); // Base::call_disp() không ảo, nhưng this trỏ đến Derived
return 0;
}
Kết quả
Calling display from base class Print function from the derived class
Giải thích
bp->call_disp()gọiBaseClass::call_disp(không ảo, binding tĩnh).- Bên trong,
this->display()tra vtable của đối tượng thực tế (DerivedClass) → gọiDerivedClass::display. - vptr (con trỏ ảo) trỏ đến vtable của lớp thực tế, được thiết lập khi constructor chạy.
Kết luận
Hàm ảo hoạt động đa hình bất kể được gọi từ đâu (hàm ảo, không ảo, constructor, destructor - trừ khi đang trong constructor/destructor của base).