member variable initialization

G

George2

Hello everyone,


I am wondering in the following code, member variable a in class B is
not put in the initialization list or constructor of B directly, but
it is initialized. How and when member variable a of class B is
created and initialized? Is constructor of B invokes constructor of a?

Output is,

In constructor A
In constructor B

Code:
#include <iostream>

using namespace std;

class A
{
public:

	A()
	{
		cout << "In constructor A" << endl;
	}
};

class B
{
public:

	A a;

	B()
	{
		cout << "In constructor B" << endl;
	}
};

int main()
{
	B b;

	return 0;
}


thanks in advance,
George
 
V

Victor Bazarov

George2 said:
I am wondering in the following code, member variable a in class B is
not put in the initialization list or constructor of B directly, but
it is initialized. How and when member variable a of class B is
created and initialized? Is constructor of B invokes constructor of a?

Yes. Since 'A' is a class type (has a user-defined c-tor), and it is
not explicitly initialised in the B's c-tor init list, the 'a' object
in B is default-initialised by invoking its c-tor, just before the
control enters the body of B::B().
Output is,

In constructor A
In constructor B

Code:
#include <iostream>

using namespace std;

class A
{
public:

A()
{
cout << "In constructor A" << endl;
}
};

class B
{
public:

A a;

B()
{
cout << "In constructor B" << endl;
}
};

int main()
{
B b;

return 0;
}

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top