user3375895
user3375895

Reputation: 1

private destructor friend function

Friend function destructs pointer, still I am able to access functions of the class with the pointer.

#include <iostream>
using namespace std;

// A class with private destuctor
class Test
{
private:
~Test() 
{
cout<<"Inside destructor"<<endl;
}

friend void destructTest(Test* );
public:
void display()
{
cout<<"I am display func:"<<this<<endl;
}
};

void destructTest(Test* ptr)
{
cout<<"In here:"<<ptr<<endl; 
delete ptr;
ptr = NULL;
}

int main()
{
    Test *ptr;
    ptr = new Test;
    destructTest (ptr);
    ptr->display();// this gets called properly!
    return 0;
}

How is it that the pointer reference holds on? I have even tried moving some parts of this code ( = new Test()) to another function just to see if it is to do with the local reference, but the reference remains till end of program!

Only If I put a ptr = NULL, after the destructTest call, it still calls the display function but gives memory location as 0.

Upvotes: 0

Views: 537

Answers (1)

Salgar
Salgar

Reputation: 7775

Your display() function is not actually accessing any of the memory that has been allocated or (now) deleted.

If you had a member variable and tried to access it, the program would be more likely to crash.

However what you are doing here is undefined behaviour, just because you deleted the object, doesn't mean that any of the memory has changed where it used to be, or maybe it has, or who knows, that's totally implementation dependant and you can not rely on it. In short, anything could happen once you dereference a deleted pointer, including emailing your cat.

Upvotes: 2

Related Questions