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.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
 o.OOOo.                   o.OOoOoo  oOoOOoOOo         
O `o oO O o .oOOo.
o O O o o O o
O o o ooOO O o O
o O O O o O o `OooOo
O o o o O o O O
o .O' O O o O O o
OooOO' OooOO `OoO'o ooOooOoO o' `OooO'

Enter the code depicted in ASCII art style.