Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- Why I can return an int for class Month

Tags:

c++

Saw the following code snippet and I have problems to understand how it works.

class Month {
public:
    static const Month Jan() { return 1; }
    ...
    static const Month Dec() { return 12; }

    int asInt() const { return monthNumber; }
private:
    Month(int number) : monthNumber(number) {}
    const int monthNumber;
}

The class is designed in this way so that the user will not get invalid month value.

Here is the question: why the static function Jan can return 1 with the return value as Month?

Thank you

Based on the comments, this class can be designed as follows:

class Month {
public:
    static const Month Jan() { return Month(1); }
    ...
    static const Month Dec() { return Month(12); }

    int asInt() const { return monthNumber; }
private:
    explicit Month(int number) : monthNumber(number) {}
    const int monthNumber;
};
like image 499
q0987 Avatar asked Dec 16 '22 20:12

q0987


2 Answers

The Month object is created automatically using the Month(int) constructor. It could/should have been written this way to be explicit:

static const Month Jan() { return Month(1); }

Note that good practice is to declare constructors that take one parameter as explicit. Indeed, these constructors can be used to perform type conversions, as you have experienced with your code. Good practice is to declare these constructors explicit, so that this automatic conversion do not occur. It would have forced you to write it as I did.

like image 93
Didier Trosset Avatar answered Dec 28 '22 22:12

Didier Trosset


Because you didn't mark your constructor as "explicit", so it can be used in an implicit conversion operation.

like image 29
MikeP Avatar answered Dec 28 '22 23:12

MikeP