I have written a small program, but main destructor is not working properly. Here is the code of the program:
#include<iostream.h>
class citizen {
private:
char* name;
char* nationality;
public:
citizen(char* name, char* nationality) {
this->name = name;
this->nationality = nationality;
}
citizen(const citizen &obj) {
name = obj.name;
nationality = obj.nationality;
}
void display() {
cout << "Name: " << name << endl;
cout << "Nationality: " << nationality << endl;
}
~citizen() {
if(name){
delete[]name;
}
if(nationality) {
delete []nationality;
}
}
};
main() {
citizen obj1("Ali", "Pakistani");
obj1.display();
{
citizen obj2 = obj1;
}
obj1.display();
system("pause");
}
What I know is that in main
function where I'm assigning state of obj1
to obj2
, from that place both of them are now pointing to same memory area. Whereas the code citizen obj2 = obj1;
is between two curly braces.
{
citizen obj2 = obj1;
}
So after execution of second curly brace, obj2
should destroy and also delete variables name
and nationality
. And when I call obj1.display();
for the second time it should display garbage on the screen.
But obj1
is still printing exact name which I have provided in constructor, even though it shouldn't be.
Please explain this behavior.