0

Why can't I do this in C++?

struct SomeStruct
{
public:
    SomeStruct(const int someInt)
    {
        m_someInt = someInt;
    }

private:
    const int m_someInt;
};

Should the private field just be a regular integer?

yekanchi
  • 801
  • 1
  • 13
  • 28

2 Answers2

9

You're assigning someInt to m_someInt, which is illegal. But initialization is okay.

struct SomeStruct
{
public:
    SomeStruct(const int someInt) : m_someInt(someInt)
    {

    }

private:
    const int m_someInt;
};

More info: Constructors and member initializer lists

frogatto
  • 27,475
  • 10
  • 76
  • 119
0

Value cannot be assigned to a const storage. It can be only initialized. In case of class member variable it would be done in initialization list.

struct SomeStruct
{
public:
    SomeStruct(const int someInt) : m_someInt(someInt)
    {

    }

private:
    const int m_someInt;
};

Sometimes in-class initialization is enough:

template <int  Val>
struct SomeStruct
{
public:

private:
    const int m_someInt = Val;
};

Usually confusion stems from the fact that programmer doesn't see difference between two cases:

// 1) Declaring storage of int object that initially  contains value 5
int a = 5; // It's a declaration.

// 2) Declaring storage of int object that contains undetermined value
int b; // Declaration 
b = 5; // Assigning a value to it. It's a statement.

In your case m_someInt = someInt; is a statement that expects lvalue before =, and m_someInt is not a legal lvalue because it is const.

Swift - Friday Pie
  • 10,991
  • 2
  • 18
  • 36