3

I have to read lines from a .txt file and want to initialize the members of my class with it. The first character in a line is always a number.

class myClass{

  private:
    const int ID;

  public:
    myClass(const int id){
       this->ID =  id;
    }

};

Doing this gives me "Provides no initializer for Kontakt::ID" for the constructor and "expression must be a modifiable Ivalue" for this->ID = id;

  • 1
    `myClass(const int id) : ID(id) {}` ? – Borgleader Apr 11 '19 at 17:09
  • Use the initialization list. It exists for a reason; to do *initialization*. Don't use the ctor body, which runs *after* initialization. And btw; that explicit `this->` is redundant. – Jesper Juhl Apr 11 '19 at 17:10
  • 2
    Fun fact: An object MUST be fully initialized before entering the body of the constructor. Even if you can assign a member inside the body of the constructor, it has already been initialized. If you assign the member later in the body, you've wasted the time spent initializing. This can be expensive, so prefer the initializer list. Sometimes it is beneficial to have a helper function: `myClass() : expensivemember(complexlogic()) {}` – user4581301 Apr 11 '19 at 17:18
  • @JesperJuhl using `this->` before members can be a style thing, indicating what is used is a member. It's similar to having a naming convention like `m_name`. With modern IDEs, people usually don't, but it's not stylistically wrong. – user904963 Nov 30 '21 at 15:20

2 Answers2

3

You have to use member initializer list for that:

myClass(const int id)
    : ID(id) { }
r3mus n0x
  • 5,954
  • 1
  • 13
  • 34
3

You must initialize const class members in the member initializer list. Here's a complete example (see online):

class myClass {
  private:
    const int ID;
  public:
    myClass(const int id) : ID(id) {
                         // ^^^^^^
    }

};

int main() {
    myClass x(42);
}

The problem is that initialization in the constructor's body is too late, all class scope members would be tried to be initialized before the code in the body executes, and there's no default initialization for the const class member variable.

If you really want a default initialization, you can do so like this (online example):

class myClass {
  private:
    const int ID = -42; // <<<
  public:
    myClass() = default; // <<<
    myClass(const int id) : ID(id) {
    }

};

int main() {
    myClass x;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190