Thread: class deleting itself

  1. #1
    return 0;
    Join Date
    Jan 2005
    Location
    Netherlands
    Posts
    89

    class deleting itself

    Code:
    #include <iostream>
    using namespace std;
    
    class Foo
    {
        public:
            void Destroy();
    } *global_foo;
    
    
    void Foo::Destroy()
    {
        delete global_foo;
    
        cout << "Still here..." << endl;
    }
    
    
    int main()
    {
        global_foo = new Foo;
        global_foo->Destroy();
    
        return 0;
    }
    What should happen when I run this? Because it runs without errors, but I'm not sure wether it's valid to do this. I mean, shouldn't the object be deleted after "delete global_foo"? Which means "Still here..." shouldn't be displayed right? But it is. Any possible side effects I should know of?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Nothing is going wrong. The fact that you deleted global_foo is still true, but you can print as many messages as you want. It has nothing to do with freeing the memory that global_foo points to.

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    88
    I think what you wrote is fine and legal because the object is only needed to call the function: not to do what's inside it.

  4. #4
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    This is basically this. I mean. Haha.

    http://www.parashift.com/c++-faq-lit...html#faq-16.15

    [16.15] Is it legal (and moral) for a member function to say delete this?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating a database
    By Shamino in forum Game Programming
    Replies: 19
    Last Post: 06-10-2007, 01:09 PM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  3. class errors
    By romeoz in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2003, 07:57 PM
  4. Deleting Data within a Structure or class
    By TankCDR in forum C++ Programming
    Replies: 1
    Last Post: 02-01-2002, 10:37 PM