Why default constructor is called

1
2
3
4
5
6
7
8
9
10
11
12
class BBB
{
    string name;
public:
    BBB(string name){this.name=name;}
}
class AAA
{
public:
    BBB b;
    AAA(string name):b(name){}
}


You know, at "BBB b" the default constructor is automatically called.
To avoid this, what we only can do is to use member initializers ,which make grammers dirty.

I don't understand why C++ just doesn't disable this automatic invocation of default construcor in this case.
If it is disabled, we need to use member initializers only when we call parent's constructor.
Last edited on
If you have a BBB object inside some other AAA object, how else is the BBB object supposed to be constructed? An AAA object can't be assumed to construct any objects it needs; that makes no sense.

You should tell us what you are trying to do and perhaps we can suggest better ways to go about it.
You can construct BBB object in AAA's constructor
In java there's no member initializer
member objects are initialized in owner object's constructor
You know, at "BBB b" the default constructor is automatically called.
To avoid this, what we only can do is to use member initializers ,which make grammers dirty.

Who, what, where? Please explain.


PS. this is pointer and thus line 5 has a syntax error.
Furthermore, default constructor of string was called there.
1
2
3
4
5
BBB::BBB(string name){ this->name=name; }
// is exactly same as
BBB::BBB(string name) : name() { this->name=name; }
// and different from
BBB::BBB(string name) : name(name) {}

Parameter and member with same name is confusing.
If the constructor was not automatically called that would be error prone because you could easily forget calling the constructor. To call the constructor explicitly I guess you would have to use the placement new syntax:
1
2
3
4
5
6
7
8
9
class AAA
{
public:
	BBB b;
	AAA(string name)
	{
		new (&b) BBB(name);
	}
};

Note that normal assignment would not work because operator= assumes the object is constructed already.

I don't think it improves anything if you could do it like that. Note that you can easily make it readable by formatting the constructor initialization list in a readable way.
1
2
3
4
5
6
SomeClass::SomeClass()
:	member1("hello"),
	member2(1, 2, 3),
	member3(100.7)
{
}


In java there's no member initializer

In Java all data members are reference variables (similar to C++ pointers). In your example b is an actual object and not a pointer/reference to one.
Last edited on
In Java all data members are reference variables

Thanks. Now I understand!!!
Topic archived. No new replies allowed.