TITLE: how to (inadvertently) call a pure virtual function PROBLEM: rcn@news.nynexst.com (Ramesh Nagabushnam) on several occasions, I have seen one of my programs quit with a message "..Pure Virtual function called.." or something to that effect. How can this happen? RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 2 Oct 95 Usually it happens because you have passed "this" from a constructor to some other function, which is generally a poor idea. Example: class abstract { public: virtual void foo() = 0; // pure virtual function abstract(); }; void somefunc(abstract* p) { p->foo(); // ordinarily OK, since there are no "abstract" objects } abstract::abstract() { somefunc(this); // bad idea, since object IS an "abstract" during construction } class concrete: public abstract { public: virtual void foo() { return; } concrete() { } }; main() { concrete c; // during construction, pure virtual is called return 0; } RESPONSE: rmartin@rcmcon.com (Robert Martin) This will happen any time that you call a pure virtual function from a constructor or destructor. The reason is simple, the virtual deployment rules of C++ state that, in a constructor or destructor, virtua functions will not deploy below the level of the currently executing constructor or destructor. class B { public: B() {Init();} virtual void Init() = 0; }; class D : public B { public: virtual void Init() {} }; main() { D d; // pure virtual function called. } When 'd' is constructed, the B::B constructor runs. It calls Init. But Init cannot be deployed below the B level since a B constructor is running. Moreover, 'Init' is pure at the B level. Thus, "pure virtual function called." If you don't like this rule, consider; it is a natural consequence of the rule in C++ that says that a member function of a class will not be called before that classes constructor has been called, or after that classes constructor has returned.