Q:

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? 

A:

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

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

