Alan Sahbegovic
Alan Sahbegovic

Reputation: 31

how to call a member function from a destructor

I'm doing work for a C++ project, but I want to know how to call a member function from a class/structure within a destructor. The rest of my project is going well, so I just need to know this to be finished with it :)

    ~Drink()
    {
        cout << "hi";
        cout << "I want to know how to summon a member function from a destructor.";
    }

    int Drink::dailyReport()
    {
        cout << "This is the member function I want to call from the destructor.";
        cout << "How would I call this function from the destructor?"
    }

Proper syntax and all would be appreciated! Examples of how to call a member function from a destructor would be lovely!

Upvotes: 3

Views: 6035

Answers (2)

Geoffrey Tucker
Geoffrey Tucker

Reputation: 670

The problem here is that you didn't prefix your destructor with Drink::

Since the destructor doesn't know what class it is supposed to be associated with (assuming it is being defined outside of the class declaration), it does not know that it even has a member function to call.

Try rewriting your code to:

Drink::~Drink() // this is where your problem is
{
    cout << "hi";
    cout << "I want to know how to summon a member function from a destructor.";
    dailyReport(); // call the function like this
}

int Drink::dailyReport()
{
    cout << "This is the member function I want to call from the destructor.";
    cout << "How would I call this function from the destructor?"
}

Upvotes: 3

jrsmolley
jrsmolley

Reputation: 419

A class destructor is basically like any other member function: you can call the class's member functions and use member variables the same way, except:

  1. Keep in mind of course that destructors are intended for cleanup and (if you're handling it manually) deallocation of resources and dynamic memory etc, so you probably shouldn't be doing much in a destructor.

  2. If/when your class becomes complex enough to use virtual functions, things become a bit trickier.

  3. Suggestion: be careful not to do anything in a destructor that has even the possibility of throwing an exception without handling it: it can introduce nasty, hard-to-find bugs.

Upvotes: 1

Related Questions