I tried to "repair" the example in this answer as to demonstrate how a pure virtual function can be called.
#include <iostream>
using namespace std;
class A
{
int id;
public:
A(int i): id(i) {}
int callFoo() { return foo(); }
virtual int foo() = 0;
};
class B: public A
{
public:
B(): A(callFoo()) {}
int foo() { return 3; }
};
int main() {
B b; // <-- this should call a pure virtual function
cout << b.callFoo() << endl;
return 0;
}
But I get no runtime error here (with C++ 4.9.2), but the output 3. I tried the same with Borland C++ 5.6.4, but there I'm getting an access violation. I think that foo()
should be pure virtual in the call of the constructor of the base class.
Who is wrong? Should I try more compilers? Am I right in my understanding of virtual functions?
cout
statement toA::callFoo()
. If we remove thecout
statement then it compiles and works. I would have to guess that the minimal example just happens to work as the pointers stay aligned. – NomologyA *a = new B;
gives a runtime error ideone.com/RV8mP8 – Bismuthinite