B-Mac
B-Mac

Reputation: 567

Function call inside the destructor's body doesn't work

There is a function that prints something and I need to call this function both explicitly in the main as well as in the destructor when the object (has to be a global one) is destroyed. However the destructor's call doesn't display in the file.

#include <iostream>
#include <fstream>

using namespace std;

class A {

public:
    friend void func(A&);
    ~A() {
        func(*this);
    }

};

A a;
ofstream out;

int main() {
    out.open("file.txt");
    func(a);
    cin.get();
    return 0;
}

void func(A& a) {
    out << "\nHello!!!\n";
}

I only see one "Hello!!!" in the file when I want two. I also haven't closed the ostream object either. Ideally, I'd want to close it after the function call in the destructor. How do I do it?

Upvotes: 0

Views: 57

Answers (1)

Philipp Lenk
Philipp Lenk

Reputation: 951

Static objects in the same translation unit are constructed in the order of their definition and destructed in reverse order, as explained here

As such, your "out" object gets destructed(and therefore closed) before a's destructor is called and tries to write to it.

Switching the declaration order fixes the problem, but is propably not a great solution and you would be better of avoiding the static, global objects alltogether. (Especially try to avoid depending on the order of their destruction).

Upvotes: 1

Related Questions