Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring readonly variables on a C++ class or struct

I'm coming to C++ from C# and const-correctness is still new to me. In C# I could declare a property like this:

class Type 
{
    public readonly int x;
    public Type(int y) 
    {
        x = y;
    }
}

This would ensure that x was only set during initialization. I would like to do something similar in C++. The best I can come up with though is:

class Type
{
private:
    int _x;
public:
    Type(int y) { _x = y; }
    int get_x() { return _x; }
};

Is there a better way to do this? Even better: Can I do this with a struct? The type I have in mind is really just a collection of data, with no logic, so a struct would be better if I could guarantee that its values are set only during initialization.

like image 516
Justin R. Avatar asked Sep 12 '13 22:09

Justin R.


1 Answers

There is a const modifier:

class Type
{
private:
   const int _x;
   int j;

public:
    Type(int y):_x(y) { j = 5; }
    int get_x() { return _x; }
    // disable changing the object through assignment
    Type& operator=(const Type&) = delete;
};

Note that you need to initialize constant in the constructor initialization list. Other variables you can also initialize in the constructor body.

About your second question, yes, you can do something like this:

   struct Type
   {
      const int x; 
      const int y;

      Type(int vx, int vy): x(vx), y(vy){}
      // disable changing the object through assignment
      Type& operator=(const Type&) = delete;
   };
like image 177
Nemanja Boric Avatar answered Sep 21 '22 12:09

Nemanja Boric