Why is the attribute c set without initialization?

This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

using namespace std;

struct C{
	C(){ cout<<"C cst" <<endl;}
	~C(){ cout<<"C dst" <<endl;}
};

struct A{
	A(){ cout<< "A cst" <<endl;}   //4.-
	~A(){ cout<< "A dst" <<endl;}
};

struct B{
	B():a(){cout<<"B cst" <<endl;}   //2.-              
	~B(){cout<<"B dst" <<endl;}

private:
	A a;    //3.-
	C c;
};


int main() {
	B b;            //1.- 
	cout<<endl;
	{
		B b1;
		cout <<endl;
	}

	return 0;
}


My understandig is the following:
1.- Here the object b is created
2.- In the constructor of B the attribute is set with null value (the stdout "B cst" is in the stack)
3.- The object a is created
4.- the stdout "A cst" is in the stack
...

According to my understandig this should is printed:
A cst
B cst
....

However when I execute the program this is printed:
A cst
C cst <- Why is the object c implicitelly initialised?
B cst

A cst
C cst
B cst

B dst
C dst
A dst
B dst
C dst
A dst

I was surprised to see that the object c is constructed. Why is the attribute c implicitelly initialised?

Thanks.
closed account (48T7M4Gy)
When you declare object B at line 26 the constructor of a B object at line 16 creates the object which has two private members of type A and C which are created - hence A then C then B

You can test this by commenting out lines 20 and/or 21 an observing the effect on the output.
@kemort Thanks for you answer.

Nevertheless I still have some doubts:
Why do you say that the object B has two private members? I associate private member with functions. Can be members also used for attributes?

More over I know that B has to attributes but only 1 is set in the construction:
line 16: B():a(){cout<<"B cst" <<endl;}

Why is then also c instantiated?

You have written:
1
2
3
4
5
struct B{
private:
	A a;
	C c;
};

i.e. each B-object contains one A and one C subobject. Member variable, or "attribute" as you call them.

You state that the subobjects B::a and B::c have private accessibility, i.e. can be accessed
only by the member functions of struct B.


On creation of an object the subobjects must be created and initialized too.
If you don't do the initialization explicitly, then default initialization is used.
closed account (48T7M4Gy)
@puertas

I think keskiverto has already said it another way but your line 19 is the start of the two private members a (type A) and c (type C). These two are part of the data structure you called and encapsulated in struct B.

You can leave out the initialisation list item :a() in line 16. All it does is initilize the private member a it doesn't have any effect if you leave it out to demonstrate what's happening here. It would only show up if you wanted to set a value for a - (which has no meaning here). Try it by leaving it out :)

I understood thanks!!
Topic archived. No new replies allowed.