Sign in to follow this  
moussen15

Calling Pure virtual methods from destructor?

Recommended Posts

why can't I do this?: class myInterface { public: virtual ~myInterface(){doYourThing();} virtual void doYourThing() = 0; }; It should be possible seeing as all the instances (ie subclass-instances) of this interface should have been required to supply an implementation for doYourThing. Thus there is absolutely no risk that it might still be virtual when the call is made. Yet I get this error message: myfilename.cpp: In destructor 'virtual myInterface::~myInterface(): myfilename.cpp:6: error: abstract virtual 'virtual void myInterface::doYourThing()' I am using g++. Thank you for your enlightening me :)

Share this post


Link to post
Share on other sites
The derived classes will have been destroyed by the time the function is called, so it just resolves to the classes own implementation. [smile]

Share this post


Link to post
Share on other sites
When a base class' destructor is called, the destructors for all derived classes have been called. You can think of it like this: at that point the type of the class is no longer the type of the derived type, it's the type of the base class, and the base class doesn't implement doYourThing() so you have a problem.

The reason for this behavior is that because the destructors for all the derived classes have been called, the member variables that the derived classes defined have also heen destroyed, so a virtual member function of the derived class should not be called since it may depend on a variable that has been destroyed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this