I understand why calling a virtual function from a constructor is bad, but I'm not sure why defining a destructor would result in a "pure virtual method called" exception. The code uses const values to reduce the use of dynamic allocation - possibly also the culprit.
#include <iostream>
using namespace std;
class ActionBase {
public:
~ActionBase() { } // Comment out and works as expected
virtual void invoke() const = 0;
};
template <class T>
class Action : public ActionBase {
public:
Action( T& target, void (T::*action)())
: _target( target ), _action( action ) { }
virtual void invoke() const {
if (_action) (_target.*_action)();
}
T& _target;
void (T::*_action)();
};
class View {
public:
void foo() { cout << "here" << endl; }
};
class Button : public View {
public:
Button( const ActionBase& action )
: _action( action ) { }
virtual void mouseDown() {
_action.invoke();
}
private:
const ActionBase& _action;
};
int main( int argc, char* argv[] )
{
View view;
Button button = Button( Action<View>( view, &View::foo ) );
button.mouseDown();
return 0;
}
ActionBase
's destructorvirtual
. See parashift.com/c++-faq-lite/virtual-functions.html#faq-20.7 – Presidentelect