I am new to C++ and learning the virtual functions and got to know that we must write virtual destructor if the class have virtual functions and the class has pointer members. Below is my code, and I am using Virtual Studio 2013RC
#include<iostream>
using namespace std;
//base and derived class with virtual function
class Parent{
protected:
const char *name;
public:
virtual void say(){ cout << "1" << endl; }
virtual void showName(){ cout << name << endl; }
Parent(){};
Parent(const char *myName) :name(myName){};
virtual ~Parent(){ delete name; cout << "Parent name deleted" << endl; }
};
class Child :public Parent{
protected:
const char *name;
public:
virtual void say(){ cout << "2" << endl; }
virtual void showName(){ cout << name << endl; }
Child(){};
Child(const char *myName) :name(myName){};
virtual ~Child(){ delete name; cout << "Child name deleted" << endl;}
};
int main(){
Child a("Tom");
return 0;
}
Or
int main(){
Parent *a = new Child("Tom");
delete a;
return 0;
}
Both will give error windows of Debug Assertion Failed.
For this case, how should I write the virtual destructor properly?
Thanks a lot
Because you try to delete a literal string pointer. You set the Child::name
member to point to the literal string "Tom"
, which is a pointer to memory created by your compiler. You should only delete
what you explicitly new
.
Also note that the Parent
and Child
classes each have a different and distinct name
member variables. When you initialize the Child::name
variable, the one in Parent
is still uninitialized.