In "C++ Primer", exercise 14.47, there is a question:
Explain the difference between these two conversion operators:
struct Integral { operator const int(); operator int() const; }
I don't know why the the answer I found on GitHub says that the first const
is meaningless, because for one conversion operator should not define return type, this const
here is unspecified, it will be ignored by the compiler. But I also found some guys say that it means the function will return a const
value.
So, I wonder which one is correct, and why?
it will be ignored by compiler.
This is because of expr#6 which states:
If a prvalue initially has the type
cv T
, whereT
is a cv-unqualified non-class, non-array type, the type of the expression is adjusted toT
prior to any further analysis.
This means that in your particular example, const int
will be adjusted to int
before further analysis since int
is a built in type and not a class type.
which one is right?
Even though the return type of the first conversion function is const int
, it will be adjusted to int
prior to any further analysis.
While the const
on the second conversion function means that the this
pointer inside that function is of type const Integral*
. This means that it(the conversion function) can be used with const
as well as non-const Integral
object. This is from class.this
If the member function is declared const, the type of this is const X*, ...