从构造函数调用虚函数和纯虚函数 [英] Invoking virtual function and pure-virtual function from a constructor

查看:549
本文介绍了从构造函数调用虚函数和纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When i invoke a virtual function from a base constructor, the compiler does not give any error. But when i invoke a pure-virtual function from the base class constructor, it gives compilation error.

考虑下面的示例程序:

#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()时调用基类中定义的纯虚函数。相反,它给出编译错误:

Here it is seen that the pure virtual function has a definition. I expected the pure virtual function defined in base class to be invoked when bptr->virtualfunc() is executed. Instead it gives the compilation error:


错误:abstract virtual`virtual void base :: virtualfunc

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

原因是什么?

推荐答案

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

C ++ 03 10.4 / 6个状态


成员函数可以从抽象类的构造函数对于正在从这样的构造函数(或析构函数)创建(或销毁)的对象,直接或间接地对一个纯虚拟函数进行虚拟调用(10.3)是未定义的。

"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。

You get an compilation error because you have not defined the pure virtual function virtualfunc() in the Base class. To be able to call it, it must have an body.

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

Anyways, calling pure virtual functions in constructors should be avoided as it is Undefined Behavior to do so.

这篇关于从构造函数调用虚函数和纯虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆