constant objects

Hello everybody

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
  #include<iostream>
using namespace std;

class ColourLight {
private:
    int val;
    int checkValue(int c) const {
        switch(c) {
        case 0:
        case 1:
        case 2:
        case 3:
            return c;
        default:
            return 0;
        }
    }
public:
    ColourLight(int c = 0)
    : val(checkValue(c)) {
    }
    void set (int c) {
        val = checkValue(c);
    }
    ColourLight value() const {
        return val;
    }
};

int main() {
    const ColourLight red = 0;
    const ColourLight redYellow = 1;
    const ColourLight yellow = 2;
    const ColourLight green = 3;
    return 0;
}


This snippet is based on an example I took from a C++ book.
The author wants to illustrate how to realize a simple enumeration without enumeration (it's a preliminary example, before the chapter about enumeration).

I can't understand why this snippet compiles without problem.

1) Here, we have a function that should return a ColourLight Type, but it returns an int type:
1
2
3
ColourLight value() const {
        return val;
    }


2) What kind of inizialization is that?
1
2
3
4
const ColourLight red = 0;
const ColourLight redYellow = 1;
const ColourLight yellow = 2;
const ColourLight green = 3;

Can you help understanding these 2 points?
Thanks
Last edited on
Topic archived. No new replies allowed.