1、作用
为了在实现多态的时候不造成内存泄露,
如果基类析构函数前不加vitual,派生类对象被销毁后,只会调用基类的析构函数,而不会去调用派生类的析构函数。
2、对于正常的函数,如果基类中声明为virtual,则派生类可以不用再写virtual
- // CPPTest.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- class Base
- {
- public:
- Base(){}
- virtual ~Base()
- {
- printf("Base Destructor!/n");
- }
- virtual void Func()
- {
- printf("Base Func!/n");
- }
- private:
- int m_iData;
- };
- class Derived : public Base
- {
- public:
- Derived(){}
- ~Derived()
- {
- printf("Derived Destructor!/n");
- }
- void Func()
- {
- printf("Derived Func!/n");
- }
- };
- class Derived2 : public Derived
- {
- public:
- Derived2(){}
- ~Derived2()
- {
- printf("Derived2 Destructor!/n");
- }
- void Func()
- {
- printf("Derived2 Func!/n");
- }
- };
- int main(int argc, char* argv[])
- {
- Base *pb = new Base;
- pb->Func();
- Base *pd = new Derived;
- pd->Func();
- Base *pd2 = new Derived2;
- pd2->Func();
- delete pb;
- delete pd;
- delete pd2;
- return 0;
- }
结果:
Base Func!
Derived Func!
Derived2 Func!
Base Destructor!
Derived Destructor!
Base Destructor!
Derived2 Destructor!
Derived Destructor!
Base Destructor!
C++虚析构函数的作用
关注
打赏