Back to Browse

virtual destructor in c++ in hindi

2.5K views
Jun 17, 2021
11:29

Virtual Destructor When we delete a derived class object using a base class pointer, then generally only base class object is destroyed without destroying the child class object. Consider the following example: #include<iostream> using namespace std; class Parent { public: Parent() { cout<<"\nThe parent class object is created..."; } ~Parent() { cout<<"\nThe parent class object is deleted..."; } }; class Child:public Parent { public: Child() { cout<<"\nThe child class object is created..."; } ~Child() { cout<<"\nThe child class object is deleted..."; } }; int main() { Parent *p; p=new Child; delete p; return 0; } When we define the destructor of Base/Parent class using virtual keyword, then it is called as virtual destructor. The virtual destructor ensures that while deleting the Child class object using base class pointer, the child object is destroyed first, then the parent object is deleted. Consider the following program: #include<iostream> using namespace std; class Parent { public: Parent() { cout<<"\nThe parent class object is created..."; } virtual ~Parent() { cout<<"\nThe parent class object is deleted..."; } }; class Child:public Parent { public: Child() { cout<<"\nThe child class object is created..."; } ~Child() { cout<<"\nThe child class object is deleted..."; } }; int main() { Parent *p; p=new Child; delete p; return 0; } Note: we can create virtual destructor but we cannot create virtual constructors.

Download

1 formats

Video Formats

360pmp415.9 MB

Right-click 'Download' and select 'Save Link As' if the file opens in a new tab.

virtual destructor in c++ in hindi | NatokHD