Calling Virtual Function from Destructor

Calling virtual function from destructor

I am going to go against the flow here... but first, I must assume that your PublicBase destructor is virtual, as otherwise the Derived destructor will never be called.

It is usually not a good idea to call a virtual function from a constructor/destructor

The reason for this is that dynamic dispatch is strange during these two operations. The actual type of the object changes during construction and it changes again during destruction. When a destructor is being executed, the object is of exactly that type, and never a type derived from it. Dynamic dispatch is in effect at all time, but the final overrider of the virtual function will change depending where in the hierarchy you are.

That is, you should never expect a call to a virtual function in a constructor/destructor to be executed in any type that derived from the type of the constructor/destructor being executed.

But

In your particular case, the final overrider (at least for this part of the hierarchy) is above your level. Moreover, you are not using dynamic dispatch at all. The call PrivateBase::FunctionCall(); is statically resolved, and effectively equivalent to a call to any non-virtual function. The fact that the function is virtual or not does not affect this call.

So yes it is fine doing as you are doing, although you will be forced to explain this in code reviews as most people learn the mantra of the rule rather than the reason for it.

Calling a virtual function from a destructor of a derived class in c++

Conceptually all the virtual functions in B are accessible in the destructor body, so your code is fine and well-defined as it is.

But your code is extremely brittle: it would be a different matter if there was a child class of B which had method overridden. In that case writing B::method(); in the destructor body of B would be sufficient.

Short answer: calling virtual methods in constructors and destructors is best avoided.

Calling virtual function from destructor - any workaround?

Can you separate control of the scope lifetime of the object from the object itself, allowing you to use RAII ?

I've tried to follow your example where base class is effectively the logic (x), derived classes are the implementation (x and open/close) and the guard class manages lifetime of open/close calls.

#include <iostream>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
namespace ExampleOpenCloseScope
{
static DWORD DoSomethingForWindows(HANDLE *noonePassesHandlesLikeThis) { *noonePassesHandlesLikeThis = reinterpret_cast<HANDLE>(1); std::wcout << L"DoSomethingForWindows()\n"; return 0; }
static void WindowsCloseHandle(HANDLE /*handle*/) { std::wcout << L"WindowsCloseHandle()\n"; }
class DeviceBase
{
int _x;
public:
bool isValid() const { return isValidImpl(); }
void x() { checkPrecondsForX(); doX(); checkPostcondsForX(); }
bool open() { return openHandle(); }
void close() { closeHandle(); }
private:
virtual bool isValidImpl() const = 0;
virtual void checkPrecondsForX() = 0;
virtual void doX() = 0;
virtual void checkPostcondsForX() = 0;

virtual bool openHandle() = 0;
virtual void closeHandle() = 0;
protected:
DeviceBase() : _x(42) {}
public:
virtual ~DeviceBase() = 0 {}
};

class DeviceWin32 : public DeviceBase
{
private:
HANDLE _handle;
virtual bool isValidImpl() const override { return _handle != NULL; }
virtual void checkPrecondsForX() override { std::wcout << L"DeviceWin32::checkPrecondsForX()\n"; }
virtual void doX() override { std::wcout << L"DeviceWin32::doX()\n"; }
virtual void checkPostcondsForX() override { std::wcout << L"DeviceWin32::checkPostcondsForX()\n"; }
virtual bool openHandle() override { std::wcout << L"DeviceWin32::openHandle()\n"; if (_handle == NULL) return DoSomethingForWindows(&_handle) == ERROR_SUCCESS; return true; }
virtual void closeHandle() override { std::wcout << L"DeviceWin32::closeHandle()\n"; if (_handle != NULL) WindowsCloseHandle(_handle); _handle = NULL; }
public:
DeviceWin32() : _handle(NULL) {}
virtual ~DeviceWin32() { std::wcout << L"DeviceWin32::~DeviceWin32()\n"; }
};

static int _do_smth_posix(int *fd) { *fd = 1; std::wcout << L"_do_smth_posix()\n"; return 0; }
static void _posix_close_fd(int /*fd*/) { std::wcout << L"_posix_close_fd\n"; }

class DeviceLinux : public DeviceBase
{
private:
int _fd;
virtual bool isValidImpl() const override { return _fd != 0; }
virtual void checkPrecondsForX() override { std::wcout << L"DeviceLinux::checkPrecondsForX()\n"; }
virtual void doX() override { std::wcout << L"DeviceLinux::doX()\n"; }
virtual void checkPostcondsForX() override { std::wcout << L"DeviceLinux::checkPostcondsForX()\n"; }
virtual bool openHandle() override { std::wcout << L"DeviceLinux::openHandle()\n"; if (_fd == -1) return _do_smth_posix(&_fd) == 0; return true; }
virtual void closeHandle() override { std::wcout << L"DeviceLinux::closeHandle()\n"; if (_fd != -1) _posix_close_fd(_fd); _fd = -1; }
public:
DeviceLinux() : _fd(-1) {}
virtual ~DeviceLinux() { std::wcout << L"DeviceLinux::~DeviceLinux()\n"; }
};

class DeviceGuard
{
DeviceBase *_device;
bool _open;
public:
DeviceGuard(DeviceBase *device) : _device(device) { _open = _device->open(); }
~DeviceGuard() { try { if (_open) _device->close(); _open = false; } catch (...) { std::wcerr << L"This ain't good\n"; } }

DeviceGuard(DeviceGuard const &) = delete;
DeviceGuard & operator=(DeviceGuard const &) = delete;
};

enum OS
{
Windows,
Linux
};
static OS GetOs() { return OS::Windows; }
void TestDevice(DeviceBase *device)
{
DeviceGuard guard(device);
device->x();
}
void Test()
{
std::wcout << L"===ExampleOpenCloseScope.Test()===\n";

DeviceBase *device;
if (GetOs() == Windows) device = new DeviceWin32();
else device = new DeviceLinux();

TestDevice(device);
delete device;
std::wcout << L"exiting ExampleOpenCloseScope.Test()\n";
}
}

The output is:

===ExampleOpenCloseScope.Test()===
DeviceWin32::openHandle()
DoSomethingForWindows()
DeviceWin32::checkPrecondsForX()
DeviceWin32::doX()
DeviceWin32::checkPostcondsForX()
DeviceWin32::closeHandle()
WindowsCloseHandle()
DeviceWin32::~DeviceWin32()
exiting ExampleOpenCloseScope.Test()

Calling virtual function from virtual destructor error C++

By the time you call the Animal destructor, the derived class (Dog/Cat) has already had its destructor called, thus it is invalid. Calling Dog::sound() would risk accessing destroyed data.

Thus the destructor call is not allowed to access derived class methods. It tries to access Animal::sound(), but it's pure virtual - hence the error.

Calling virtual method from destructor - workaround?

Destructors are the right place to release acquired resources, but each class is responsible to release its own resources. Resources acquired by class A should not (and just can not) be released by class Base.

Defining virtual destructors allows class A's destructor to be called when deleting a pointer to class Base pointing to a class A object

Base* p = new A;
delete p; // Both A and Base destructors are sequencially called!

So to achieve proper resource release you just have to release each class' resources in its own destructor.

Indirect call of virtual function from Destructor

In a destructor, the dynamic type of this is that of the current class, not the original dynamic type of the object. See e.g. http://www.artima.com/cppsource/nevercall.html.



Related Topics



Leave a reply



Submit