user7125505
user7125505

Reputation:

Static data member in c++

#include <iostream>
using namespace std;

class A
{
    int x;
public:
    A() { cout << "A's constructor called " << endl; }
};

class B
{
    static A a;
public:
    B() { cout << "B's constructor called " << endl; }
    static A getA() { return a; }
};

A B::a; // definition of a

int main()
{
    B b1, b2, b3;
    A a = b1.getA();

    return 0;
}

Output:

A's constructor called 
B's constructor called 
B's constructor called 
B's constructor called 

Here even when A is not the base class of B, why A's constructor is being invoked first?

Upvotes: 0

Views: 45

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

The reason for why A's constructor is called once, and first, as part of your code is as follows:

  1. B have a static field of type A (not a pointer, a real, live, instance, of type A).
  2. As such, any usage of B should require it to be statically initialized once
  3. Thus the static field, of type A, will need to be initialized
  4. Thus, A's constructor is called in order to do so.

Upvotes: 1

Related Questions