Consider the following 2 programs.
#include <iostream>
using std::cout;
class Base {
public:
virtual void f()=0;
void g() {
f();
}
virtual ~Base() { }
};
class Derived : public Base
{
public:
void f() {
cout<<"Derived::f() is called\n";
}
~Derived() {}
};
class Derived1 : public Base
{
public:
void f() {
cout<<"Derived1::f() is called\n";
}
~Derived1() { }
};
int main() {
Derived1 d;
Base& b=d;
b.g();
b.f();
}
Compiles & runs fine and gives expected outcome..
#include <iostream>
using std::cout;
class Base {
public:
virtual void f()=0;
Base() {
f(); // oops,error can't call from ctor & dtor
}
};
class Derived : public Base
{
public:
void f() {
std::cout<<"Derived::f() is called\n";
}
};
int main() { Derived d; Base& b=d; b.f(); }
The above program fails in compilation. Why is it allowed to call a pure virtual function from the member function of the same class in which the pure virtual function is declared? Is it fine to do this or is it undefined behavior because derived class still doesn't provide an implementation of the pure virtual function? Why can't a pure virtual function be called from constructor & destructor of the same class? I know that Derived class constructors can call pure virtual functions of the base class. What does the C++ standard say about this?