Reputation:
#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
Reputation: 391336
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
).B
should require it to be statically initialized onceA
, will need to be initializedA
's constructor is called in order to do so.Upvotes: 1