Question

As I understand it, there are the conditions under which a pure-virtual method may not be implemented on a child class, but the child class can be invoked without it resulting in a build error.

I was unable to simulate this. Does someone have any insight into how to make this happen? I've done a number of searches, but haven't been able to turn-up anything.

Was it helpful?

Solution

It occurs when a virtual function is called in the constructor of a base class.

#include <iostream>

class Base
{
public:
    Base() { g();} 
    virtual ~Base() {}

    void g() { f(); }
    virtual void f() = 0;
};

class Derived : public Base
{
public:
    Derived() : Base() {}
    ~Derived() {}

    void f() { std::cout << "Derived f()" << std::endl; }
};

int main()
{
    Derived d; // here we have the call to the pure virtual function

    return 0;
}

EDIT:

The main problem is: when a Derived object is constructed, the object starts as a Base, then the Base::Base constructor is executed. Since the object is still a Base, the call to f() (via g()) invokes Base::f and not Derived::f. After the Base::Base constructor completes, the object then becomes a Derived and the Derived::Derived constructor is run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top