为什么派生类指针指向基类可以调用派生类成员函数?

时间:2020-10-29 02:16:01

标签: c++ class

#include <iostream>
using namespace std;

struct Base {
    void doBase() {
        cout << "bar" << endl;
    }
};

struct Derived : public Base {
    void doBar() {
        cout << "bar" << endl;
   }
};

int main()
{
    Base b;
    Base* b_ptr = &b;
    Derived* d_ptr = static_cast<Derived*>(b_ptr);
    d_ptr->doBar(); //Why there is no compile error or runtime error?
    return 0;
}

该程序的输出为bar\n

d_ptr实际上是在调用派生类成员函数时指向基类。

这是未定义的行为还是其他原因?

1 个答案:

答案 0 :(得分:1)

是的,这是未定义的行为。

因为您使用了static_cast,所以没有编译时错误-这是一种告诉编译器“我比您更了解类型的方法”。您告诉您的对象是Derived。您对编译器撒谎-这是未定义的行为。

它之所以起作用,是因为doBar()不使用任何Derived成员。

相关问题