From a previous question I know that when calling ~base()
in a derived class, it first constructs a temporary base object, then invokes temporary base operator~()
on the temporary object, and finally destroys the temporary object.
However, when the base class does not have an operator~
, calling base::~base()
in the derived class can still invoke the base class's destructor.
Why does an error occur when the base class has an operator~
?
#include <iostream>
using namespace std;
class base
{
public:
base(){cout << "constructor base \n";}
~base(){cout << "destructor base \n";}
void operator~(){cout << "operator ~ \n";}
};
class derived : public base
{
public:
derived(){cout << "constructor derived \n";}
~derived(){base::~base();cout << "destructor derived \n";}
};
Compiler version information:
g++.exe (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Error:
cmd /c chcp 65001>nul && C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g "D:\Valkyrie-text\simple text\text.cpp" -o "D:\Valkyrie-text\simple text\text.exe"
D:\Valkyrie-text\simple text\text.cpp: In destructor 'derived::~derived()':
D:\Valkyrie-text\simple text\text.cpp:15:28: error: no matching function for call to 'derived::~derived()'
~derived(){base::~base();cout << "destructor derived \n";}
^
D:\Valkyrie-text\simple text\text.cpp:7:5: note: candidate: 'base::~base()'
~base(){cout << "destructor base \n";}
^
D:\Valkyrie-text\simple text\text.cpp:7:5: note: candidate expects 1 argument, 0 provided
As multiple people noted in comments, this code is "correct", that is, the compiler should not complain:
~derived(){base::~base();cout << "destructor derived \n";}
Since your old gcc doesn't accept it, you could use different syntax which does the same:
~derived(){this->~base();cout << "destructor derived \n";}
However, the language calls base class destructor automatically, and you shouldn't interfere with this.
I did some tinkering for fun and discovered that this bug was fixed in gcc version 10 (in 2020). It probably took so long to find this bug because the code is utterly useless and as such no one tested it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With