Net function call from Base Ctor

Consider the following code example:

#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 a pure virtual function bar()in the base class, which is redefined in the derived class. A pure virtual function bar()has no definition in the base class.

Now focus on the Line1, Line2, Line3, and Line4.

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

Questions:

  • Why Line2and Line4do not provide compilation errorfor the same reason, the above-mentioned instructions I understand. Challenges in Line2and Line4ultimately will only challenge linker-error.

  • Line3 , , run-time exception?

Real-Life UB, :

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

+5
6

- Undefined , .

:
++ 03 10.4/6:

"- ( ) , (10.3) , , ( ) ( ) undefined."

++ Undefined :

[defns.undefined] 1.3.12 Undefined

, , . Undefined , . [ : Undefined , , ( ), ( ). Undefined; .]

+5

undefined; , , , , .

, ; 1, , , 1.

, , . 2 4.

3 , , , . , , this . .

, undefined .

, , Base::bar() bptr->Base::bar(). undefined.

+6

. 3 , , , .

+1

?

Vc10 gcc 4.6 . gcc , base:: bar() .

, , bocs, virtual from constructor, Undefined Behavior.

+1

Weird ++ fact: (, , ) .

void base::bar() { cout << "Wuh?"; }

, 2 4 .

, : base::bar();

( ) . ; undefined.

0

undefined, , , . bar() ; undefined. ( Base::bar(), , ). , , ; g++, , , .

, , , . 3 , 1 2 -.

And the statement that "a pure virtual function cannot be called from the constructor" is false. The only time a problem occurs is dynamic resolution allows a pure virtual function. A call with a static permission (provided that it exists) is fine, and a call to a pure virtual function in the base class is fine if the dynamic resolution does not appear to be a pure virtual function in the derived class, whose constructor has or is started.

0
source

All Articles