c++ - Destructor does not destroy objects -
i have written small program, main destructor not working properly. here code of 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 know in main
function i'm assigning state of obj1
obj2
, place both of them pointing same memory area. whereas code citizen obj2 = obj1;
between 2 curly braces.
{ citizen obj2 = obj1; }
so after execution of second curly brace, obj2
should destroy , delete variables name
, nationality
. , when call obj1.display();
second time should display garbage on screen.
but obj1
still printing exact name have provided in constructor, though shouldn't be.
please explain behavior.
your delete[]
s invoke undefined behavior because you're attempting destroy string literals. anything can happen.
even if allocated memory yourself, you'd still run undefined behavior because you'd attempting access memory you've deleted:
obj1.display(); { citizen obj2 = obj1; } obj1.display(); // illegal
because didn't define assignment operator, compiler-generated 1 used, assigns pointers same memory - memory destroy , attempt access.
Comments
Post a Comment