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

I saw the following piece of code, 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 so that the user does not receive an invalid month value.

Here's the question: why can a static Jan function return 1 with a return value like a month?

thanks

Based on the comments, this class can be constructed 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; }; 
+4
source share
4 answers

A Month object is created automatically using the Month(int) constructor. It could / should have been written in such a way as to be explicit:

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

Note that it is good practice to declare constructors that accept a single parameter as explicit . In fact, these constructors can be used to perform type conversions, as was the case with your code. It is good practice to declare these constructors explicit so that this automatic conversion does not happen. It will make you write it like me.

+12
source

Because you did not mark your constructor as "explicit", so you can use it in an implicit conversion operation.

+1
source

I think the constructor is used in implicit casting.

Those. The constructor can create a Month object from an integer. The compiler automatically uses this to create the returned Month object.

I consider this a bad practice, and many compilers should give a warning. If this compiles for you, try changing the compiler warning level to be more strict.

0
source

Your constructor is private. If you want to build Month instances with int, you must declare this constructor public

-1
source

All Articles