如何将虚拟析构函数删除派生类内存 [英] How to virutal destructor will delete the derived class memory
本文介绍了如何将虚拟析构函数删除派生类内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
计划:
Program:
//============================================================================
// Name : revision6.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
class innova {
public:
innova() {
cout << "innova constructor called" << endl;
}
virtual void speed() {
cout << "The speed of innova is: 160kmph" << endl;
}
virtual ~innova() {
cout << "innova destructor called" << endl;
}
};
class nano : public innova {
public:
nano() {
cout << "nano constructor called" << endl;
}
void speed() {
cout << "The speed of nano is: 60kmph" << endl;
}
~nano() {
cout << "Nano destructor called" << endl;
}
};
int main() {
innova *inobj = new nano;
inobj->speed();
delete inobj;
return 0;
}
输出:
Output:
innova constructor called
nano constructor called
The speed of nano is: 60kmph
Nano destructor called
innova destructor called
我的问题:
在main函数中我删除了innova指针(删除inobj),这里它调用了两个类析构函数,我不知道它是如何使用虚拟析构函数在内部调用的。
你能否澄清这个问题。
提前致谢
Paramaraj
My question:
In main function I am deleting the innova pointer (delete inobj), Here its calling the both class destructor , i dont how it is calling internally using virtual destructor.
Could you please clarify this problem.
Thanks in advance
Paramaraj
推荐答案
最有可能通过 vtables
发生(据我所知,这些细节留给实施者)。这是一种语言功能,您可以在这里找到一些信息 [ ^ ]。
It happens most likely through vtables
(such details are left to implementators, as far as I know). This is a language feature, you may find some info here[^].
因为构造函数可以被调用名字,但在destrctors的情况下,它不是真的。 ..
自动调用析构函数。
As constructors can be called by name but in case of destrctors it is not true. ..
destructor is called automatically.
#include <iostream>
using namespace::std;
class Base
{
public:
Base(){cout << "Base constructor" << endl;}
virtual ~Base(){cout << "Base destructor" << endl;} // virtual
virtual void f(){cout << "f in the Base class" << endl;}
void g(){cout << "g in the Base (invoked)" << endl;}
};
class Derived:public Base
{
public:
Derived(){cout << "Derived constructor" << endl;}
~Derived(){cout << "Derived destructor" << endl;}
void f(){cout << "f in the Derived class" << endl;}
void g(){cout << "g in the Derived (invoked)" << endl;}
};
int main()
{
Base *x,*y;
x = new Base;
y = new Derived;
x->f();
y->f();
x->g();
y->g(); // g of Base called again, as this is not declared as virtual ..
delete x;
delete y; // again destructor of Base called, not the Derived ..
// hence constructor is called by name, but the destructors don't,
// so, the destructor of Base class should be virtual ..
return 0;
}
这篇关于如何将虚拟析构函数删除派生类内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文