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?
You could use member initializer list, as you did for
m_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.
You are using a
>c++11
compiler and using in class non static member initialization as demonstrate with the lineint m_y = 2*m_x;
. To use the same initialization mechanism with constructable object, you have to use the uniform initialization syntax, using braces :