Search code examples
c++functioncallvirtualpure-virtual

C++ pure virtual function call doesn't throw run-time exception?


It's said that in C++ constructor function, as long as the object has not finished construction, shouldn't call virtual function, or else there'll be "pure virtual function call error" thrown out. So I tried this:

#include<stdio.h>
class A{
    virtual void f() = 0;
};

class A1 : public A{
public:
    void f(){printf("virtual function");}
    A1(){f();}
};
int main(int argc, char const *argv[]){
    A1 a;
    return 0;
}

compile it with g++ on windows, it works and prints

virtual function

So how to make my program throw out "pure virtual function call" exception?

Thanks!


Solution

  • You are not getting the "pure virtual method call" exception because A::f() is not being called.

    A1's constructor is calling its own A1::f() method, which is perfectly safe to do during A1's construction.

    The issue with calling a virtual method in a constructor has to do with a base class constructor calling a derived class method, which doesn't work since the derived portion of the object being constructed doesn't exist yet.

    So, to get the exception you want, you need to call f() in A's constructor rather than in A1's constructor.