c++ - 从构造函数调用虚函数和纯虚函数

标签 c++ constructor compiler-errors virtual-functions dynamic-binding

当我从基本构造函数调用虚函数时,编译器不会给出任何错误。但是当我从基类构造函数调用纯虚函数时,它会出现编译错误。

考虑下面的示例程序:

#include <iostream>

using namespace std;
class base
{
   public:
      void virtual virtualfunc() = 0;
      //void virtual virtualfunc();
      base()
      {
         virtualfunc();
      }
};

void base::virtualfunc()
{
   cout << " pvf in base class\n";
}

class derived : public base
{
   public:
   void virtualfunc()
   {
      cout << "vf in derived class\n";
   }
};

int main()
{
   derived d;
   base *bptr = &d;
   bptr->virtualfunc();

   return 0;
}

这里可以看出纯虚函数是有定义的。我希望在执行 bptr->virtualfunc() 时调用基类中定义的纯虚函数。相反,它给出了编译错误:

error: abstract virtual `virtual void base::virtualfunc()' called from constructor

这是什么原因?

最佳答案

不要从构造函数中调用纯虚函数,因为它会导致未定义的行为

C++03 10.4/6 状态

"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."

你得到一个编译错误,因为你没有在 Base 类中定义纯虚函数 virtualfunc()。为了能够调用它,它必须有一个 body 。

无论如何,应该避免在构造函数中调用纯虚函数,因为这样做是未定义的行为。

关于c++ - 从构造函数调用虚函数和纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8642363/

相关文章:

c++ - 错误11 error LNK2005 : "class cv::Mat imageOutput" (? imageOutput@@3VMat@cv@@A) 已经定义在My​​Form.obj

c++ - 如何使用 Windows API 更改时区设置

c++ 隐式复制构造函数是否复制数组成员变量?

c++ - 为类的数据成员声明范围

compiler-errors - COBOL 程序的编译问题

parsing - 解析错误Unity 3D

c++ - 为什么 gcc 允许使用大于数组的字符串文字初始化 char 数组?

c++ - 派生类仍然是抽象的

python - 如何强制库(pybind11)包含Python3中的<Python.h>?

c++ - 为什么拷贝构造函数不需要检查输入对象是否指向自己?