| 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
.
|
|
|
|

|
Related Articles |
|
|