The Wayback Machine - https://web.archive.org/web/20241115213403/https://www.geeksforgeeks.org/pure-virtual-destructor-c/
Open In App

Pure Virtual Destructor in C++

Last Updated : 02 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you must specify a destructor body.

When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance. 

Note: Only Destructors can be Virtual. Constructors cannot be declared as virtual, this is because if you try to override a constructor by declaring it in a base/super class and call it in the derived/sub class with same functionalities it will always give an error as overriding means a feature that lets us to use a method from the parent class in the child class which is not possible. 

Can a destructor be pure virtual in C++? 
Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor. 

Why a pure virtual function requires a function body?

The reason is that destructors (unlike other functions) are not actually ‘overridden’, rather they are always called in the reverse order of the class derivation. This means that a derived class destructor will be invoked first, then the base class destructor will be called. If the definition of the pure virtual destructor is not provided, then what function body will be called during object destruction? Therefore the compiler and linker enforce the existence of a function body for pure virtual destructors. 
 
Example:

CPP




// C++ Program to demonstrate a pure virtual destructor
#include <iostream>
using namespace std;
 
// Initialization of base class
class Base {
public:
    virtual ~Base() = 0;
    // Pure virtual destructor
};
 
// Initialization of derived class
class Derived : public Base {
public:
    ~Derived() { cout << "~Derived() is executed"; }
};
 
// Driver Code
int main()
{
    // base class pointer which is
    // allocating fresh storage
    // for Derived function object's
    Base* b = new Derived();
    delete b;
    return 0;
}


The linker will produce the following error in the above program. 

test.cpp:(.text$_ZN7DerivedD1Ev[__ZN7DerivedD1Ev]+0x4c): 
undefined reference to `Base::~Base()'  error: ld returned 1 exit status

Now if the definition for the pure virtual destructor is provided, then the program compiles & runs fine.

CPP




// C++ program to demonstrate if the value of
// of pure virtual destructor are provided
// then the program compiles & runs fine.
 
#include <iostream>
 
// Initialization of base class
class Base {
public:
    virtual ~Base() = 0; // Pure virtual destructor
};
Base::~Base() // Explicit destructor call
{
    std::cout << "Pure virtual destructor is called";
}
 
// Initialization of derived class
class Derived : public Base {
public:
    ~Derived() { std::cout << "~Derived() is executed\n"; }
};
 
int main()
{
    // Calling of derived member function
    Base* b = new Derived();
    delete b;
    return 0;
}


Output

~Derived() is executed
Pure virtual destructor is called

How did the above code work MAGICALLY?

This basically works because the destructors will be called recursively bottom to up if and only if the value is passed in the virtual destructor. So vtable is a table containing pointers of all virtual functions that the class defines, and the compiler provides vptr to the class as a ‘hidden pointer‘ that points to the ideal vtable, so the compiler makes use of an accurate or correct index, calculated at compile-time, to the vtable which will dispatch the correct virtual function at runtime.

It is important to note that a class becomes an abstract class(at least a function that has no definition) when it contains a pure virtual destructor.

Example:

CPP




// C++ program to demonstrate how a class becomes
// an abstract class when a pure virtual destructor is
// passed
 
#include <iostream>
class Test {
public:
    virtual ~Test() = 0;
    // Test now becomes abstract class
};
Test::~Test() {}
 
// Driver Code
int main()
{
    Test p;
    Test* t1 = new Test;
    return 0;
}


The above program fails in a compilation & shows the following error messages. 

[Error] cannot declare variable 'p' to be of abstract type 'Test' 
[Note] because the following virtual functions are pure within 'Test': 
[Note] virtual Test::~Test() 
[Error] cannot allocate an object of abstract type 'Test' 
[Note] since type 'Test' has pure virtual functions

This article was contributed by Meet Pravasi.



Previous Article
Next Article

Similar Reads

Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
How to detect Stack Unwinding in a Destructor in C++?
What is Stack Unwinding? Stack unwinding is the process of executing destructors for all local objects when an exception propagates out of a function. It happens when an exception is thrown and not caught within the same function. When this occurs, the destructors for all objects with automatic storage duration declared in that function are called
4 min read
Private Destructor in C++
Destructors with the access modifier as private are known as Private Destructors. Whenever we want to prevent the destruction of an object, we can make the destructor private. What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private. For dynamically created objects, it
4 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Order of Constructor/ Destructor Call in C++
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that t
4 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 min read
Pure Functions
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions
2 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
C++ | Virtual Functions | Question 1
Which of the following is true about virtual functions in C++. (A) Virtual functions are functions that can be overridden in derived class with the same signature. (B) Virtual functions enable run-time polymorphism in a inheritance hierarchy. (C) If a function is 'virtual' in the base class, the most-derived class's implementation of the function i
1 min read
C++ | Virtual Functions | Question 2
Predict output of the following program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->show(); Base &br = *bp; br.show(
1 min read
C++ | Virtual Functions | Question 3
Output of following program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp, b; Derived d; bp = &d; bp->show(); bp = &b; bp->show();
1 min read
C++ | Virtual Functions | Question 5
#include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; int main(void) { Base b; Base *bp; return 0; } (A) There are compiler errors in lines "Base b;" and "Base bp;" (B) There is compiler error in line "Base b;" (C) There is compiler error in line "Base bp;" (D) No compiler Error Answer: (B) Explanation: Sinc
1 min read
C++ | Virtual Functions | Question 6
Predict the output of following program. #include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived : public Base { }; int main(void) { Derived q; return 0; } (A) Compiler Error: there cannot be an empty derived class (B) Compiler Error: Derived is abstract (C) No compiler Error Answer: (B) Explanat
1 min read
C++ | Virtual Functions | Question 7
#include<iostream> using namespace std; class Base { public: virtual void show() = 0; }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Derived d; Base &br = d; br.show(); return 0; } (A) Compiler Error in line "Base &br = d;" (B) Empty Output (C) In Derived Answer: (C)
1 min read
C++ | Virtual Functions | Question 14
Can a constructor be virtual? Will the following program compile? #include <iostream> using namespace std; class Base { public: virtual Base() {} }; int main() { return 0; } (A) Yes (B) No Answer: (B) Explanation: There is nothing like Virtual Constructor. Making constructors virtual doesn't make sense as constructor is responsible for creati
1 min read
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; } (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
1 min read
C++ | Virtual Functions | Question 10
#include<iostream> using namespace std; class Base { public: Base() { cout<<"Constructor: Base"<<endl; } virtual ~Base() { cout<<"Destructor : Base"<<endl; } }; class Derived: public Base { public: Derived() { cout<<"Constructor: Derived"<<endl; } ~Derived() { cout<<
1 min read
C++ | Virtual Functions | Question 11
Can static functions be virtual? Will the following program compile? #include<iostream>  using namespace std;      class Test {    public:       virtual static void fun()  { } }; (A) Yes (B) No Answer: (B) Explanation: Static functions are class specific and may not be called on objects. Virtual functions are called according to the pointed o
1 min read
C++ | Virtual Functions | Question 12
Predict the output of following C++ program. Assume that there is no alignment and a typical implementation of virtual functions is done by the compiler. #include <iostream> using namespace std; class A { public: virtual void fun(); }; class B { public: void fun(); }; int main() { int a = sizeof(A), b = sizeof(B); if (a == b) cout <<
1 min read
C++ | Virtual Functions | Question 13
#include <iostream> using namespace std; class A { public: virtual void fun() { cout << "A::fun() "; } }; class B: public A { public: void fun() { cout << "B::fun() "; } }; class C: public B { public: void fun() { cout << "C::fun() "; } }; int main() { B *bp = new C; bp->fun(); return 0; } (A
1 min read
C++ | Virtual Functions | Question 14
Predict the output of following C++ program #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<" In Base \n"; } }; class Derived: public Base { public: void show() { cout<<"In Derived \n"; } }; int main(void) { Base *bp = new Derived; bp->Base::show(); // Note the use of
1 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Target Corporation Interview Experience | On-Campus Virtual Hiring
Round 1 - Online test This round has MCQ s regrading English reading comprehension, Reasoning, logical, Quantitative(Numerical) and technical questions. Technical questions were related to computer science domain. This round also has 2 coding questions: Counting the duplicate elements in an arrayOptimal oil flow problem Both questions had 2 public
3 min read
ARM Interview Experience for Intern (On-Campus Virtual 2020)
ARM talent acquisition team visited our campus virtually for an intern role in the verification domain. There were totally 3 rounds, Round 1 (Written Test) : 30 Aptitude (Time & Work, Time and Distance, percentages, profit and loss, SI & CI covered all major topics in aptitude)70 Technical (Digital, C basics & Guessing the output, OS co
2 min read
Practice Tags :
three90RightbarBannerImg