Inspired by this question, I tried the following code:
struct A {
virtual void doit() const = 0;
};
struct B : public A {
virtual void doit() const;
};
str
Oh, it's very invalid.
Consider:
#include
using namespace std;
struct A {
virtual ~A() { cout << "~A" << endl; }
virtual void doit() const = 0;
};
struct B : public A
{
~B() override { cout << "~B" << endl; }
void doit() const override { cout << "A::doit" << endl; }
};
struct C : public A
{
~C() override { cout << "~C" << endl; }
virtual void doit() const { cout << "C::doit" << endl; }
};
void foo(bool p)
{
cout << "foo( " << p << ")" << endl;
const A &a = (p ? static_cast(B()) : static_cast(C()));
a.doit();
}
auto main( int argc, char* argv[] ) -> int
{
cout << boolalpha;
foo( true );
cout << endl;
foo( false );
}
Output in Coliru Viewer, using g++ 4.8:
foo( true) ~B ~A pure virtual method called terminate called without an active exception bash: line 7: 16922 Aborted (core dumped) ./a.out
It's UB so any explanation could be true, but one can be reasonably sure, without looking at the assembly, that what happens is:
A
, which is abstract.A
is called.