Object destroyed still can be called, why ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eagerlearner
    New Member
    • Jul 2007
    • 29

    Object destroyed still can be called, why ?

    I am learning the C++ oop, why when I create an object and delete it but it still can be called even though it's destroyed. Check this simple code here. Thank you.

    Code:
    #include <iostream>
    using namespace std;
    
    class h
    {
    public:
    	h(){ cout << "h called\n";};
    	void write() { cout << "write\n";}
    	~h(){cout << "h destroyed\n"; };
    };
    
    int main()
    {
    
    	h* pH = new h();
    	pH->write();
    	delete pH;
    	pH = NULL;
    	pH->write();
    
    	return 0;
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    No the object can't still be called. You have invoked undefined behaviour by dereferencing the NULL pointer.

    It appears to work because the function you have invoked does not access any member variables so is not trying to use any data locations that may have been allocated. However run this code on a different system or use a different compiler and you may well get a different result.

    In C++ (and C) just because something is compiling does not mean it is working, it is the responsibility of the programmer to make sure that they do not create code that invokes undefined behaviour.


    Try adding a data member to your class and initialising when you construct the object, then delete the object and set the pointer to NULL and try to access the data member and see what happens.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      In addition to the previous explanation, change your function to:

      [code=cpp]
      virtual void write() { cout << "write\n";}
      [/code]

      ... and see what happens.

      kind regards,

      Jos

      Comment

      • eagerlearner
        New Member
        • Jul 2007
        • 29

        #4
        Yeah, when I put another member data and try to access it in write, my program hang. I can understand already for this, but about the virutal function that JosAH posted, why declaring virtual function make it hang as well ? How does it work ? Thank you.

        Comment

        • Banfa
          Recognized Expert Expert
          • Feb 2006
          • 9067

          #5
          As soon as you have a virtual function a virtual function table has to be stored in the object. This is a table of pointers to functions, the function is called by referencing the pointer in the table. As soon as you delete the object the table is deallocated so when it is used to try and access the write function you get an invalid referenced.

          Comment

          Working...