Home > Back-end >  Constructors static keyword use
Constructors static keyword use

Time:12-28

I read so many definitions of keyword 'static' and I still find it very confusing. Output of this program should be :

1 2 1 2 3 4 1 1 2 3 4 8 7 6 5 1 2 6 5

I understand how global members are called,but when the program reaches the main and static D d; I get all confused. Thank you in advance to anyone willing to explain!

#include <iostream>
using namespace std;
struct D {
  D() { cout << "1" << endl; }
  ~D() { cout << "5" << endl; }
};
class C {
public:
  D d;
  C() { cout << "2" << endl; }
  ~C() { cout << "6" << endl; }
};
struct B {
  C c;
  B() { cout << "3" << endl; }
  ~B() { cout << "7" << endl; }
};
struct A {
  B b;
  A() { cout << "4" << endl; }
  ~A() { cout << "8" << endl; }
};
extern A a;
C c;
int main() {
  static D d;
  A{};
  C{};
  return 0;
}
A a;
extern B b;

CodePudding user response:

For your example, I'm getting

1 2
1 2 3 4
1
1 2 3 4
8 7 6 5
1 2 6 5
5 8 7 6 5 6 5

I broke the output down in groups that correspond to paragraphs that follow.

First, the global variable C c; is constructed. This first constructs its member variable of type D, which prints 1; then C's constructor prints 2. That's the first 1 2 accounted for.

Then, the global variable A a; is constructed. Even though the definition is after main, global variables are constructed before main is entered. This first constructs the member of type B, which in turn constructs a member of type C, which we already know prints 1 2. Then B's constructor prints 3 and finally A's constructor prints 4. This is the next 1 2 3 4 accounted for.

Then main runs, and it first constructs static D d;, which prints 1.

Then the temporary A{} is constructed, which we already know prints 1 2 3 4. Then this temporary is destroyed. Destructors always run in the reverse order of construction, hence 8 7 6 5

Then the temporary C{} is constructed and immediately destroyed. We already know C's construction prints 1 2, and destruction prints 6 5.

And finally, main exits, and the static D d and the two global variables are destroyed in the reverse order of construction. They printed 1 2 1 2 3 4 1 on the way up, so they now print 5 8 7 6 5 6 5 on the way down.


In this example, nothing will change if static keyword is removed from static D d;. In main function specifically, static local variables are rather pointless.

CodePudding user response:

If it does not make sense, I usually declare a variable as static. I find static great for scenarios where I might involve counting the origination of such objects.

It depends on the situation, for most cases I always use static to count how many Objects of a particular class was instantiated.

  • Related