C++ | Virtual Functions | Question 9
Can a destructor be virtual?
Will the following program compile?
#include <iostream> using namespace std; class Base { public: virtual ~Base() {} }; int main() { return 0; } |
chevron_right
filter_none
(A) Yes
(B) No
Answer: (A)
Explanation: A destructor can be virtual. We may want to call appropriate destructor when a base class pointer points to a derived class object and we delete the object. If destructor is not virtual, then only the base class destructor may be called. For example, consider the following program.
// Not good code as destructor is not virtual
#include<iostream>
using namespace std;
class Base {
public:
Base() { cout << "Constructor: Base" << endl; }
~Base() { cout << "Destructor : Base" << endl; }
};
class Derived: public Base {
public:
Derived() { cout << "Constructor: Derived" << endl; }
~Derived() { cout << "Destructor : Derived" << endl; }
};
int main() {
Base *Var = new Derived();
delete Var;
return 0;
}
Output on GCC:
Constructor: Base
Constructor: Derived
Destructor : Base
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
Recommended Posts:
- C++ | Virtual Functions | Question 1
- C++ | Virtual Functions | Question 2
- C++ | Virtual Functions | Question 3
- C++ | Virtual Functions | Question 10
- C++ | Virtual Functions | Question 14
- C++ | Virtual Functions | Question 7
- C++ | Virtual Functions | Question 5
- C++ | Virtual Functions | Question 12
- C++ | Virtual Functions | Question 11
- C++ | Virtual Functions | Question 4
- C++ | Virtual Functions | Question 13
- C++ | Virtual Functions | Question 6
- C++ | Virtual Functions | Question 14
- Can virtual functions be inlined?
- Can virtual functions be private in C++?

