Is it possible to create an object outside the initializer list? (I have an idea, I have seen it in another post, but I am not sure)
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Bar
{
int x = 0;
public:
Bar(int _x): x(_x){}
}
//
class Foo
{
Bar bar1;
Bar bar2;
public:
Foo(int x1, int x2) : bar1(x1)//how to create the bar2 outside the initializer list?
{
//how to do it here?
}
}
There's a problem: the Foo(/**/) constructor tries to call the default Bar constructor for bar2, but it finds nothing! ofc, I can add the default constructor to the Bar class and there would be no problems, but I would like to call the other constructor, not in the initializer list
When object is created it will defaul-initialize all members which you can re-assign in constructor body.
For those who want to create members using non-default constructor member initializer list was created.
So no, you can not do that. Why don't you want to use initializer list as was designed during language creation?
When you create an object of a class, all the data members get created automatically. You can't defer that creation to a later point - say, later within the class's constructor. The only control you have is to specify which constructors are used for those data members, with which arguments, in - you guessed it - the initialiser list.
If you need to delay creation of those component objects, you could have the data members be pointers to the objects, initialise them to null/0, and then dynamically allocate those objects at the point you want to create them.
Is there any particular reason why you can't just use the initialiser list to specify the constructor for bar2 ?