Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > member variable initialization

Reply
Thread Tools

member variable initialization

 
 
George2
Guest
Posts: n/a
 
      12-18-2007
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
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      12-18-2007
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;
> }
>
>


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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
initialization of array as a member using the initialization list aaragon C++ 2 11-02-2008 04:57 PM
error C2614: 'CYYYRegister' : illegal member initialization:'CRequest' is not a base or member Angus C++ 1 03-06-2008 11:38 AM
global variable vs static member initialization order n.torrey.pines@gmail.com C++ 10 03-15-2007 02:21 PM
Confused on class member variable initialization Randy C++ 5 01-13-2006 01:39 PM
How to initialize an array member in the member initialization list? jut_bit_zx@eyou.com C++ 3 10-10-2005 12:10 AM



Advertisments