0

I am trying to access the functions in a class using pointers allocating memory using 'new'. But I noticed a different behavior. Once, the object was deallocated using 'delete' and NULL referenced, it is still able to access the functions, but not the variables. When I try to do it, I receive Segmentation Fault. Can someone explain? Thanks in advance!

#include <iostream>
using namespace std;

class A
{
    public:

        int ba;

        A()
        {
            ba=10;
        }

        void func1()
        {
            cout<<"func1 is called\n";
        }

        void func2()
        {
            cout<<"func2 is called\n";
        }
};

int main()
{

    A *ptr=new A();
    ptr->func1();
    cout<<ptr->ba;
    delete ptr;
    ptr=NULL;

    ptr->func2();
    //cout<<ptr->ba;
    return 0;

}
Oleksiy
  • 37,477
  • 22
  • 74
  • 122
  • 2
    Sometimes when you try to steal things, people won't notice you. It doesn't make it any less wrong. – R. Martinho Fernandes Jul 31 '13 at 09:45
  • Translating what @R.MartinhoFernandes said to c++ language: Accessing *anything* through a NULL pointer or a `delete`d pointer is Undefined Behaviour, and so not allowed. But sometimes it will appear to work. Still don't do it. – BoBTFish Jul 31 '13 at 09:54

0 Answers0