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.