Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uninitialized constant members in classes

Tags:

c++

This is probably a ridiculously easy question, but I've been searching around for the answer for a while yet can't seem to figure this out. I'm trying to initialize a constant variable constant pointer in a class. Here is the header file:

class Scheduler{
  public:
  Scheduler();
  explicit Scheduler( unsigned long * );

  private:
  const unsigned long *const thresh;

};

And here is the constructor for the class

Scheduler::Scheduler( unsigned long * threshold ):
  thresh(threshold)
{}

When I attempt to compile this code I run into this error:

scheduler.cpp: In constructor ‘Scheduler::Scheduler()’:
scheduler.cpp:3: error: uninitialized member ‘Scheduler::thresh’ with ‘const’ type ‘const long unsigned int* const’

Multiple sources online discussing constant member variables in constructors for member variables point to using initializer lists. I think I'm doing what I'm supposed to, but apparently it's still no good. Can anyone see what's wrong?

like image 358
kei-clone Avatar asked Dec 03 '10 09:12

kei-clone


2 Answers

You must initialize your constant member in the initialization list of ALL constructors. You are doing it only for the one with an argument. Do it for the default one too, and everything will be fne. In this particular case, either initialize your thresh with 0, or disable the default constructor.

like image 110
Armen Tsirunyan Avatar answered Sep 29 '22 18:09

Armen Tsirunyan


The problem is in the default constructor, it should be

Scheduler::Scheduler() : thresh(0) {}

or not be implemented at all.

like image 23
Johan Kotlinski Avatar answered Sep 29 '22 17:09

Johan Kotlinski