且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

来自Base Ctor的纯虚函数调用

更新时间:2022-12-29 09:32:11

/ strong>&编译器可以***地显示任何行为。



参考:

C ++ 03 Standard 10.4 / 6:


可以从抽象类的构造函数(或析构函数)调用成员函数;直接或间接对虚拟函数进行虚拟调用(10.3)


C ++标准定义了未定义的行为:



[defns.undefined] 1.3.12未定义的行为

$ b $例如在使用错误的程序结构或错误的数据时可能出现的行为,本国际标准没有对其施加任何要求。当本国际标准省略对行为的任何明确定义的描述时,也可以预期未定义的行为。 [注意:允许的未定义行为的范围包括完全忽略具有不可预测的结果的情况,在以文件化的环境特征(有或没有发出诊断消息)的翻译或程序执行期间行为,终止翻译或执行(随着诊断消息的发出)。许多错误的程序结构不会产生未定义的行为;他们需要诊断。]


Consider the following sample code:

#include <iostream>

using namespace std;

class base
{
   public:
      base()
      {
         bar(); //Line1
         this->bar(); //Line2
         base *bptr = this; 
         bptr->bar(); //Line3
         ((base*)(this))->bar(); //Line4
      }

      virtual void bar() = 0;
};

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

int main()
{
   derived d;
}

The above code has pure virtual function bar() in base class which is overriden in the derived class. The pure virtual function bar() has no definition in base class.

Now focus on Line1, Line2, Line3 and Line4.

I understand : Line1 gives compilation error, because pure virtual function cannot be called from ctor.

Questions:

  1. Why does Line2 and Line4 give no compilation error for the same reason mentioned in I understand statement above?. The calls in Line2 and Line4 will eventually cause linker-error only.

  2. Why does Line3 give neither compilation error nor linker error but gives run-time exception only ?

Real-Life example of UB when Pure virtual function call through constructor:

Calling an Pure virtual function from constructor is an Undefined Behavior & the compiler is free to show any behavior.

Reference:
C++03 Standard 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."

The C++ standard defines Undefined behavior in:

[defns.undefined] 1.3.12 undefined behavior

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements. Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior. [Note: permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message). Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed. ]