1
#include<iostream>
#include<string>
using namespace std;

class Human{
    private:
       int *age;
       string *name;
    public:
        Human(string iname,int iage)
        {
            name=new string;
            age=new int;
            *name=iname;
            *age=iage;          
        }
        void display()
        {
            cout<<"Name "<<*name<<endl<<"Age "<<*age<<endl;
        }
        ~Human(){
            delete name;
            delete age;
            cout<<"Released all memories"<<endl;
        }

};
int main()
{
    Human *pallavi= new Human("pallavi",21);
    pallavi->display();
    delete pallavi;
    pallavi->display();
    return 0;
}

I have written a simple program that creates an object of class Human. The destructor is specified to delete both the data variables, i.e., int age and string name. But on calling the destructor("delete pallavi"), and displaying the variables again, the output I receive is:

Name
Age 21

Of course, the whole output is this:

Name pallavi
Age 21
Released all memories
Name
Age 21.

My question is, shouldn't the destructor release the memories? Should that not mean that on displaying the object a second time(after calling the destructor), Name and age should display garbage values? Why is the output showing no values for Name and 21 for age?

  • 2
    As an aside, you'd don't need to use pointers for your member variables, just type them as `int` and `string`. – Sean Jun 23 '16 at 09:27
  • 1
    if you just starting development, and use not so old compiler, take a look at [smart pointer](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one) – Garf365 Jun 23 '16 at 09:29
  • 1
    Possible duplicate of [C++ delete - It deletes my objects but I can still access the data?](http://stackoverflow.com/questions/1930459/c-delete-it-deletes-my-objects-but-i-can-still-access-the-data) – Tadeusz Kopec Jun 23 '16 at 09:31

3 Answers3

7

The destructor is doing what it ought to, but the behaviour on using the pointer pallavi after you've deleted it is undefined.

The compiler can do anything, including printing some of your object. It might also eat your cat.

Presumably you're only using pointer members in your class as an exercise. Doing so "in reality" is pointless for int and std::string, and is even harmful: instances of your class are no longer trivially copyable.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
1

You are referring to memory that has already been deleted, this is what is called undefined behavior in C++.

C++ does not set the memory to zero when you delete it from the heap.

Damian
  • 3,719
  • 3
  • 31
  • 63
0

After delete, the object pointed to by the ptr is in undefined state. Accessing it is undefined beavior until you assign a valid object's address to the ptr again.

lorro
  • 4,949
  • 15
  • 25