c++ - 为什么这不是纯虚函数的调用?

标签 c++ pure-virtual

我试图“修复”this answer 中的示例以演示如何调用纯虚函数。

#include <iostream>
using namespace std;

class A
{
    int id;
public:
    A(int i): id(i) {}
    int callFoo() { return foo(); }
    virtual int foo() = 0;
};

class B: public A
{
public:
    B(): A(callFoo()) {}
    int foo() { return 3; }
};

int main() {
    B b; // <-- this should call a pure virtual function
    cout << b.callFoo() << endl;
    return 0;
}

但我没有收到运行时错误 here (with C++ 4.9.2) ,但输出 3。我对 Borland C++ 5.6.4 进行了同样的尝试,但我遇到了访问冲突。我认为foo()在基类构造函数的调用中应该是纯虚的。

谁错了?我应该尝试更多的编译器吗?我对虚函数的理解是否正确?

最佳答案

您的代码具有未定义的行为:在初始化所有基类之前调用​​对象(即使是非虚拟对象)的成员函数是 UB。 C++14 (n4140) 12.6.2/14,强调我的:

Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined. ...

ctor-initializer: 之后的整个列表。 mem-initializer 是此列表的一个元素。

关于c++ - 为什么这不是纯虚函数的调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780171/

相关文章:

C++ 持久性生物操作

c++ - 从 llvm IR 中的寄存器中获取存储的值

c# - C++ 纯虚函数使类规模更大

c++ - 信任返回值优化

c++ - std::string 和格式字符串

C++ 抽象基模板类非 Void 方法

c++抽象类在非纯虚函数中使用纯虚函数

C++11接口(interface)纯虚析构函数

具有动态回调函数类型的 C++ 模板类

c++ - 下层 std::vector<std::string>