-2

I want to have an int associated with my class that is set when the user of this class instantiates it.

class MyClass {
public:
  MyClass(int x);
private:
  const int x;
};

To initialize this constant, I try to use the contructor (Java style):

MyClass::MyClass(int x) {
  this->x = x;
}

However, my compiler doesn't quite like it this way, and I get the following:

const.cxx: In constructor ‘MyClass::MyClass(int)’:
const.cxx:3:1: error: uninitialized const member in ‘const int’ [-fpermissive]
 MyClass::MyClass(int x) {
 ^
In file included from const.cxx:1:0:
const.h:8:13: note: ‘const int MyClass::x’ should be initialized
   const int x;
             ^
const.cxx:4:11: error: assignment of read-only member ‘MyClass::x’
   this->x = x;
           ^

What is the C++ way to initialize an instantiated constant based on the constructor a la Java?

EDIT: I saw the question marked as duplicate; that thread failed to mention you could use the constructor's parameters in the initializer list, since it only use numeric literals in all the examples.

2mac
  • 1,609
  • 5
  • 20
  • 35
  • 1
    Use an [initialiser list](http://en.cppreference.com/w/cpp/language/initializer_list): `MyClass::MyClass(int x) : x(x) {}` – Biffen Oct 14 '15 at 11:49
  • 3
    And BTW, use that for non-const members too... – Karoly Horvath Oct 14 '15 at 11:52
  • Use _initialization_, not assignment. – Emil Laine Oct 14 '15 at 12:29
  • This is not a duplicate of the question. The other question asks about initialising a `const int` in the declaration of the class, whereas this is asking about passing a parameter to initialise it. – Tas Aug 11 '18 at 11:39

1 Answers1

3

You can use what's called an initializer list in the constructor's function signature:

MyClass::MyClass(int x) : x(x) {
}
2mac
  • 1,609
  • 5
  • 20
  • 35
AnatolyS
  • 4,249
  • 18
  • 28