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
Line2
andLine4
give nocompilation error
for the same reason mentioned inI understand
statement above?. The calls inLine2
andLine4
will eventually causelinker-error
only.Why does
Line3
give neither compilation error nor linker error but givesrun-time exception
only ?
Real-Life example of UB when Pure virtual function call through constructor:
Line1
is removed. There is only linker error – Logue