Skip to main content

Pure virtual method called

Posted in

I managed to make a pure virtual method to be called. I'm not kidding, I'm serious and I mean it. I do realize that such behaviour is erroneous in its nature, but nevertheless, lets get an understanding of why this happened and how.

Here's the situation (simplified). I have two classes like these:

class A
    virtual void f() = 0;
class B : public A
    virtual void f() { /*...*/ }

In the constructor of B I call f(). Everything compiles just fine. I run the program and it crashes with "Pure virtual method called".

How can this be? The answer is simple:
1) The pure virtual method (at least in case of GCC) is implemented in a special way, so that it prints "Pure virtual method called" and then crashes.

and the most important

2) the C++ standard states that calling the virtual function in the constructor is an undefined behaviour.

That's why be careful and watch for functions your are calling in a derived class' constructor.

Post new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 o.     O           .oOOOo.    OooOOo.           o 
Oo o .oOOo. .O o. O `O O
O O O O o O o O O o
O o o o O o O .o oOo O
O o O OoOOo. o O oOooOO' o o
o O O O O O Oo o o O O
o Oo O o `o O' O o o
O `o `OooO' `OoooO Oo o' `oO Oo

Enter the code depicted in ASCII art style.