const variables in constructor

hey guys I have a const variable in my year class and I want to initialise it when the class is created but for some reason when I try this I get an error

is there anyway you can initialise const variables in a constructor?

I also can't give it a default value in its header.


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


class Year
{
    public:
        Year();
        Year(int x);
        virtual ~Year();

    protected:

    private:
        const int y;
};

#endif // YEAR_H


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23


#include "Year.h"

Year::Year()
{



}


Year::Year(int x)
: y(x)
{
    //ctor
}

Year::~Year()
{
    //dtor
}






C:\Users\User\control\main.cpp|10|error: uninitialized const member in 'const int' [-fpermissive]|

another example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23


#ifndef YEAR_H
#define YEAR_H

class Year
{
    public:
        const int mac = 2018;

        Year();
        Year(int x);
        virtual ~Year();

    protected:

    private:
        int y;

};

#endif // YEAR_H


how in the heck do you declare a const variable or type??

when doing it in one .cpp file(all closses and functions in one file) it works fine but it seems like it is impossible to declare a const in a class
You seem to be almost there:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

class Year
{
    public:
        Year();
        Year(int);
        Year(int, float);
        virtual ~Year();
        const float pi {3.14}; // C++11 allows initializer in definition

    protected:

    private:
        const int y;
};

int main()
{
  Year one;
  Year two( 7, 2.7 );
  Year three( 13 );
}

Year::Year()
 : y(42) // must initialize the const to some default
{
}

Year::Year(int x)
 : y(x)
{
}

Year::Year(int x, float f)
 : pi(f), y(x)
{
}

Year::~Year()
{
}
Topic archived. No new replies allowed.