下面通过一个父类的指针,去释放一个子类的对象.
//
// main.cpp
// C++虚析构函数
//
// Created by 扆佳梁 on 16/8/2.
// Copyright © 2016年 Eric. All rights reserved.
//
#include <iostream>
#include "string.h"
using namespace std;
class A{
public:
A(){
cout<<"A()"<<endl;
p = new char[20];
strcpy(p, "aaaaaaa");
}
virtual ~A(){
cout<<"~A()"<<endl;
delete [] p;
}
private:
char *p;
};
class B: public A{
public:
B(){
cout<<"B()"<<endl;
p = new char[20];
strcpy(p, "bbbbbbb");
}
~B(){
cout<<"~B()"<<endl;
delete [] p;
}
private:
char *p;
};
class C : public B{
public:
C(){
cout<<"C()"<<endl;
p = new char[20];
strcpy(p, "cccccc");
}
~C(){
cout<<"~C()"<<endl;
delete [] p;
}
private:
char *p;
};
void deleteA(A* a){
delete a;
}
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
C *c = new C();
deleteA(c);
return 0;
}