TITLE: calling a pure virtual (Newsgroups: comp.lang.c++.moderated, 4 May 97) TAYLOR: Alastair Taylor > > <5k4rdj$jps@netlab.cs.rpi.edu>... > > > I'm getting a runtime error 'pure virtual function called'. SZONYE: Bradd W. Szonye > > The most common way to cause this kind of error is to call a virtual member > > function (directly or indirectly) from the base class constructor. KEANE: Tom Keane > > I tried the following in Visual C++ 4.2. > Calling the virtual function from within the constructor or > destructor generates a link-time error. CLAMAGE: Steve Clamage The results of calling a pure virtual function are undefined. A link-time error is reasonable for direct calls from a ctor or dtor to an undefined pure virtual function. A pure virtual function will never be called via the virtual function mechanism. The only way to call one is to use a non-virtual call to the actual function. Example: class T { ... void virtual g() = 0; ... } t; class U : public T { ... } *u; t.g(); // non-virtual call of T::g u->T::g(); // non-virtual call of T::g If function g has been defined (you are allowed to provide a body for a pure virtual function), it will be called. If not, you will probably get an error at link time or run time. The implementation is not required to diagnose the error. As I said, the results are undefined. You can get an attempted (not actual) call to a pure virtual function via the virtual function mechanism through improper program design, without using any dangerous code like unchecked casts. Example: class B { ... virtual void f() = 0; ... }; void foo(B* b) { ... b->f(); ... } You cannot create objects of type B, so function foo should be safe. The actual object type passed to foo will be of some type derived from B which has a non-pure version of f. The exception is if foo is called from a ctor or dtor of B (or of a class derived from B in which f is still pure virtual). Suppose a B ctor or dtor contains this call to foo: foo(this); In that case, foo will attempt a virtual call to B::f. Even if B::f is defined, the function cannot be called that way, and you have an error. Most compilers report "pure virtual function called" at run time, but the standard does not require a diagnostic message. A reasonable rule to prevent errors of this kind is never to pass "this" out of a constructor or destructor.