0
#include <iostream>
using namespace std;

class BaseClass
{
public:
    BaseClass(int i)
    {
        data = i;
        cout << "_____BaseClass()____" << endl;
    }

    ~BaseClass()
    {
        data = -99;
        cout << "_____~BaseClass()____" << endl;
    }

    void Fun()
    {
        cout << "_____Fun()____" << data << endl;
    }

    int data;
};

int main()
{
    BaseClass *b = NULL;
    {
        BaseClass b1(300);
        b = &b1;
    }

    b->Fun();
    return 0;
}

Instance b1 is created in a segment and its life is limited to that segment. I am not able to understand how the data and methods are accessible even after destructor.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • 2
    This is undefined behaviour. Everything could happen. It could crash, print `"_____Fun()____"` or a message by Cthulhu himself. – Zeta Aug 18 '15 at 10:59
  • An important thing to remember here is that this code is likely to have specific behavior (the one you observer) even though the standard says it's undefined. This can lead you to a false sense of correctness - only to get your code broken at the most unfortunate momemnt. – skyking Aug 18 '15 at 11:09
  • 3
    possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – moooeeeep Aug 18 '15 at 11:11
  • @moooeeeep Thanks for finding the dupe; tried looking for it in vain. – legends2k Aug 18 '15 at 11:12

1 Answers1

1

C++ as a language gives some guarantees and in many areas leaves things undefined. This means, for some code, the standard doesn't mandate any behaviour and anything, as a result, can be done by the compiler. You're in such a situation.

I am not able to understand how the data and methods are accessible even after destructor.

Once the object is destroyed, accessing it, via a pointer (or something else), is undefined. You being able to access it in some instance of the program doesn't matter. In some other situation you may not be able to - changing the machine, the memory management scheme, or any other environmental factor may make the program crash, hang, etc. i.e. the language doesn't guarantee anything here.

As a general rule, you should never write code that invoke undefined behaviour, unless you're trying to learn something.

Community
  • 1
  • 1
legends2k
  • 31,634
  • 25
  • 118
  • 222
  • Yes, I was trying something and just hit this undefined behavior. I then checked on multiple compilers but got same behavior. But I am satisfied with the answer. Thank you. – Yogesh Sharma Aug 22 '15 at 06:49