member variable initialization

Discussion in 'C++' started by George2, Dec 18, 2007.

  1. George2

    George2 Guest

    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
     
    George2, Dec 18, 2007
    #1
    1. Advertising

  2. 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
     
    Victor Bazarov, Dec 18, 2007
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    3
    Views:
    873
    Peter_Julian
    Oct 10, 2005
  2. Randy
    Replies:
    5
    Views:
    382
    JustBoo
    Jan 13, 2006
  3. Replies:
    10
    Views:
    1,171
    Victor Bazarov
    Mar 15, 2007
  4. Angus
    Replies:
    1
    Views:
    2,684
  5. aaragon
    Replies:
    2
    Views:
    633
    James Kanze
    Nov 2, 2008
Loading...

Share This Page