Tuesday, December 19, 2017

Destructor and Scope in C++

Java's finalize method (ie, not the same thing as Java's finally) is said to be similar to the destructor in C++ with the caveat that there is no guarantee that the finalize method will run. I wondered if the same was true for C++ destructors.

The following code shows the destructor in C++ classes does run. Also in this example, I used parentheses to create a scope in the second function and show how the scope effects the time at which the destructors are executed. Note the difference between func1 and func2.
#include <iostream>
using namespace std;

int n = 1;

class A
{
  private:
    int age;
  public :
    A()
    {
      cout << "   A constructor" << endl;
    }
    ~A()
    {
      cout << "   A *destructor*" << endl;
    }
};

class B
{
  private:
    A *bsa;
  public:
    B(A *a)
    {
      cout << "   B constructor" << endl;
      bsa = a;
    }
    ~B()
    {
      cout << "   B *destructor*" << endl;
    }
};

void func1() {
  A a;
  B b(&a);
  cout << n++ << ". objects created in f1" << endl;
  cout << n++ << ". end of f1" << endl;
}

void func2() {
  {
    A a;
    B b(&a);
    cout << n++ << ". objects created in f2" << endl;
  }
  cout << n++ << ". end of f2" << endl;
}

int main() {
  cout << n++ << ". calling function 1" << endl;
  func1();
  n = 1;
  cout << n++ << ". calling function 2" << endl;
  func2();
  cout << n++ << ". end of program" << endl;
}

Commands to compile, link and run followed by program output
$ g++ -std=c++14 -c -o blocked_scope.o blocked_scope.cpp
$ g++ -o blocked_scope blocked_scope.o
$ ./blocked_scope
1. calling function 1
   A constructor
   B constructor
2. objects created in f1
3. end of f1
   B *destructor*
   A *destructor*
1. calling function 2
   A constructor
   B constructor
2. objects created in f2
   B *destructor*
   A *destructor*
3. end of f2
4. end of program