在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的指针,针对每个对象实例进行维护。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志