kei-clone
kei-clone

Reputation: 329

Uninitialized constant members in classes

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?

Upvotes: 12

Views: 19622

Answers (3)

BuschnicK
BuschnicK

Reputation: 5454

Your code works for me (MSVC2010) - as I believe it should. What compiler are you trying this with?
The only complaint a compiler may/should have with the code is a warning that the automatic copy constructor and assignment operator cannot be created because of the const member.

Upvotes: 0

Johan Kotlinski
Johan Kotlinski

Reputation: 25729

The problem is in the default constructor, it should be

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

or not be implemented at all.

Upvotes: 6

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132974

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.

Upvotes: 17

Related Questions