Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   member variable initialization (http://www.velocityreviews.com/forums/t561998-member-variable-initialization.html)

George2 12-18-2007 01:16 PM

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


thanks in advance,
George

Victor Bazarov 12-18-2007 02:21 PM

Re: member variable initialization
 
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




All times are GMT. The time now is 04:56 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.