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:
-
Why does
Line2andLine4give nocompilation errorfor the same reason mentioned inI understandstatement above?. The calls inLine2andLine4will eventually causelinker-erroronly. -
Why does
Line3give neither compilation error nor linker error but givesrun-time exceptiononly ?
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:
The C++ standard defines Undefined behavior in:
[defns.undefined] 1.3.12 undefined behavior