To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

traffic_lights.cpp 1.73 KB
Newer Older
Erick Turricelli's avatar
Erick Turricelli committed
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

class Trafficlight {
    public:
        enum light { green, orange, red};

        Trafficlight (light l = red) : id_(counter_++), state_(l) {
            std::cout << "Constructing " << id_ << std::endl;
        }
        Trafficlight(const Trafficlight& rhs) : id_(counter_++), state_(rhs.state_) {
            std::cout << "Copy constructing " << id_ << " from " << rhs.id_ << std::endl;
        }
        Trafficlight& operator=(const Trafficlight& rhs) {
            std::cout << "Assigning " << rhs.id_ << " to " << id_ << std::endl;
            if(this!=&rhs) {state_ = rhs.state_;} // if the 2 objects are different, assign the color
            return *this;
        }
        ~Trafficlight() { std::cout << "Decustricting " << id_ << std::endl;}

        void print_state() const;
        
    private:
        static int counter_;
        const int id_; // Unique ID
        light state_;    
};

int Trafficlight::counter_ = 0;

void Trafficlight::print_state() const {
    switch (state_)
    {
    case Trafficlight::red:
        std::cout << "red" << std::endl;
    case Trafficlight::orange:
        std::cout << "orange" << std::endl;        
        break;
    case Trafficlight::green:
        std::cout << "green" << std::endl;  
        break;       
    default:
        std::cout << "broken?!" << std::endl;
        break;
    }
}

int main() {
    Trafficlight a(Trafficlight::green);
    Trafficlight* b_ptr = new Trafficlight(Trafficlight::orange);
    Trafficlight c(a);
    Trafficlight d = *b_ptr;
    Trafficlight e;
    e = a;
    Trafficlight & f = a;

    a.print_state();
    b_ptr -> print_state();
    c.print_state();
    d.print_state();
    e.print_state();
    f.print_state();

    delete b_ptr;

    return 0;
}