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.
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 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) {}
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.