0

I am new to C++, and my question might be trivial, but I wasn't able to find a solution.

I have two classes, S and L. S looks like this:

class S
{
private:
    int m_x;

public:
    S(int x) : m_x(x)
    {
    }

    int m_y = 2*m_x;   // some random action in S
};

Now I have a second class L, where I want to initialize an S-object:

class L
{
private:
    S s(10);   // 10 is just some random value
    int m_y;
public:
    L(int y): m_y(y)
    {
    }

// ignore the rest for now.
};

This produces an error error: expected identifier before numeric constant at the line of initialization of s(10).

I don't understand why I can't do that. How could I fix this? What if I wanted to initialize the object S s(m_y) instead?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
DominikS
  • 231
  • 3
  • 12

2 Answers2

7

You could use member initializer list, as you did for m_y:

L(int y): s(10), m_y(y)
{
}

Or use default initializer list from C++11, but note it's only supported for brace or equals initializer, not including the parenthesis one.

class L
{
private:
    S s{10};   // or S s = S(10);
    int m_y;
public:
    L(int y): m_y(y) // s is initialized via default initializer list
                     // m_y is initialized via member initializer list
    {
    }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thanks a lot! Is there one way preferable over the other? – DominikS Jul 27 '17 at 17:39
  • @DominikS If you want to initialize `s` from the constructor's parameter (like `m_y`), or your compiler doesn't support C++11, you have to use member initializer list. Otherwise (i.e. initialize `s` with default value) both work fine. – songyuanyao Jul 28 '17 at 01:48
1

You are using a >c++11 compiler and using in class non static member initialization as demonstrate with the line int m_y = 2*m_x;. To use the same initialization mechanism with constructable object, you have to use the uniform initialization syntax, using braces :

class L
{
private:
    S s{10};   // use braces
    int m_y;
public:
    L(int y): m_y(y)
    {
    }

// ignore the rest for now.
};
galop1n
  • 8,573
  • 22
  • 36