当在 C++ 中的非虚拟函数内调用虚拟函数时会发生什么
在本部分,我们将讨论 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
从输出中,我们可以理解,即使在非虚拟函数内调用虚拟函数时,多态行为仍然有效。调用哪个函数是在运行时通过应用 vptr 和 vtable 决定的。
vtable - 这是每个类维护的函数指针表。
vptr - 这是每个对象实例维护的 vtable 指针。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP