Initialize const member in a class

Is it possible to initialize a const member in a class?

Normally, I would make it static const and initialize it right in the .h, but in this case I don't want to make it static. Every time I try to initialize, I get an error. Is there a simple way to do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef Maze_h
#define Maze_h

#include <string>

class Maze
{

public:
        ...

private:
        const int r = 9;
        const int c = 9;

        int exit_row;
        int exit_column;
};
#endif 
I think you can do this in the member initializer list of the constructor. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Hi
{
public:
   Hi()
   : num(10)
   {
        cout << "Now in constructor" << endl;
   }

private:
   const int num;

}
Last edited on
Thank you for the response!

But does it have to be in the .h file? My constructor is in my .cpp. When I tried what you said, I received a whole bunch of errors.
Topic archived. No new replies allowed.