Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition of classes

Tags:

c++

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?

like image 591
heater Avatar asked Dec 28 '22 00:12

heater


2 Answers

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
{
}
like image 183
Thomas Avatar answered Jan 14 '23 12:01

Thomas


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;
};
like image 41
Lightness Races in Orbit Avatar answered Jan 14 '23 11:01

Lightness Races in Orbit