Reputation: 165
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
Upvotes: 1
Views: 2809
Reputation: 4402
When writing:
Parent *a = new Child("Tom");
the string "Tom"
is defined as a literal, this means it's a basic unit like 0-9
, for example if you look at your executable you can actually find it there, they are final and you can't change them in any way (like you can't redefine 1
to 2
).
You can't change literals therefore alternating string literal in any way (like delete
) will cause errors and segmentation faults, since it's like changing your own executable you are currently running (the executable don't have this permissions).
Upvotes: 1
Reputation: 25457
You try to delete a char
pointer which is not a complex object. Simple basic rule: for each new
there must be a delete
to free memory.
In your case you are trying to free a const char
.
Upvotes: 0
Reputation: 409404
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.
Upvotes: 5