1

Possible Duplicate:
What will happen when I call a member function on a NULL object pointer?

#include <iostream>
#include <string>

using namespace std;

class myClass{
private:
        int *x, *y, *z;

public:
        myClass();
    ~myClass();
    void display();
    void math(int,int,int);
};


void myClass::math(int x,int y,int z){
    this->x = new int;
    this->y = new int;
    this->z = new int;

    *this->x = x;
    *this->y = y;
    *this->z = z;

    cout << "result: " << (x*y)+z << endl;
}

myClass::~myClass(){
    delete x;
    delete y;
    delete z;
}

void myClass::display(){
    cout << x << y << z << endl;
}

myClass::myClass(){
    x=0;
    y=0;
    z=0;
}


int main()
{
    myClass myclass;
    myClass *myptr;
    myptr = new myClass();

        myclass.math(1,1,1);

myptr->math(1,1,1);

delete myptr;

myptr->math(1,1,1);  **//why does this still print?**



int t;
cin >> t;

 }

:::OUTPUT:::

result: 2

result: 2

result: 2

I am just messing around in C++ trying to learn more. I wanted to see what exactly the delete operator does. Why is it that I still get a third output of "result: 2" after deleting the object?

Community
  • 1
  • 1
Instinct
  • 2,201
  • 1
  • 31
  • 45
  • Because (a) you didn't delete the *code*; only the memory of the object that was using it, and (b) it is entirely undefined behavior. – WhozCraig Nov 03 '12 at 05:34
  • That's why it is advisable to nullify a pointer right after deleting it. – imreal Nov 03 '12 at 05:36
  • @Nick: No, that's why it's advisable to not use raw pointers for code with ownership semantics. – Mankarse Nov 03 '12 at 05:51
  • Deallocating does not exactly delete the memory pointed, it simply marks it as unused, which means that using it directly afterwards COULD still work, provided that another program hasn't reserved that block of memory. – Jean-Marie Comets Nov 03 '12 at 10:22

2 Answers2

4

The object memory probably was not overwritten by something else yet. Do not do such things, it is undefined behavior

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
3

that's Undefined behaviour. May demons fly out of your nose.

There is another facet to that. When an object is deleted it won't be removed from memory until its overwritten by other objects that may be created after that. So even if its marked to be recycled, the data(pointed to by the pointer) could be still as it was at the time of deallocation. But there is no guarantee that it will not be used. Which is why its undefined behaviour.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78