member variable initialization



 DEVELOP > c-Plus-Plus > member variable initialization

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "George2"
Date: 18 Dec 2007 07:16:17 AM
Object: member variable initialization
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;
}
[/Code]
thanks in advance,
George
.

User: "Victor Bazarov"

Title: Re: member variable initialization 18 Dec 2007 08:21:00 AM
George2 wrote:

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;
}

[/Code]

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER