How come, when setting up class composition, contained classes can be called with a default constructor but not with one that takes parameters?
That's kind of confusing; let me offer an example.
#include "A.h"
class B
{
private:
A legal; // this kind of composition is allowed
A illegal(2,2); // this kind is not.
};
Assuming both the default constructor and one that takes 2 integers exists, only one of these is allowed. Why is this?
It is allowed for sure, but you just need to write it differently. You need to use the initializer list for the composite class's constructor:
#include "A.h"
class B
{
private:
A legal; // this kind of composition is allowed
A illegal; // this kind is, too
public:
B();
};
B::B() :
legal(), // optional, because this is the default
illegal(2, 2) // now legal
{
}
You can provide constructor parameters, but you are initialising your members wrong.
#include "A.h"
class B
{
private:
int x = 3; // you can't do this, either
A a(2,2);
};
Here's your solution, the ctor-initializer
:
#include "A.h"
class B
{
public:
B() : x(3), a(2,2) {};
private:
int x;
A a;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With