0

Isn't the destructor of the MyPointer class suppose to destroy the ptr object and all of its members? it seems like the destructor ran but for i don't understand why the 'number' of ptr still exists after the destructor ran.

#include <iostream>

using namespace std;

int* integerptr;

class MyPointer{
public:
    MyPointer(int arg);
    ~MyPointer();
    int number;
};

MyPointer::MyPointer(int arg):
    number(arg)
    {}

MyPointer::~MyPointer(){
    cout<<"Object Destroyed"<<endl;
}

int create_obj(){
    MyPointer ptr(3);
    integerptr=&ptr.number;
    cout<<integerptr<<"-->"<<*integerptr<<endl;
    return 0;
}
int main()
{
    create_obj();
    cout<<integerptr<<"-->"<<*integerptr<<endl;
    return 0;
}

Here is the output from the terminal:

0x61fefc-->3
Object Destroyed
0x61fefc-->3
Rexi
  • 97
  • 1
  • 1
  • 5
  • 1
    undefined behavior – Danh Dec 30 '16 at 09:16
  • Using the destructor doesnot necessarliy mean that the object will be destroyed. It means that you should not access that variable again. Whenever more memory is needed the freed memory might be used. But nothing is predetermined. – GAURANG VYAS Dec 30 '16 at 09:20
  • Reassigning `integerptr` to another value (e.g. garbage or null) after destruction is a waste of time. Memory occupied by `integerptr` is now just marked as free. – Schtolc Dec 30 '16 at 09:22
  • Destruction of object doesn't clear memory, where it was placed. Access to this place after destruction will be wrong (undefined behaviour) – nikniknik2016 Dec 30 '16 at 09:22

0 Answers0