2

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0xDkXy
  • 23
  • 4
  • 1
    `const` only affects objects: It says the value of an object will not be changed through this type. An object is memory that can be changed to represent different values, so `const` says no such changes will be made using this `const` type. A value is just a single value, not memory that can change. If, in `x * y * z`, `x` is 3 and `y` is 5, then `x * y` is 15, and there is no way that some other value could be stored in `x * y`; `x * y` does not designate any memory that can change. So a `const int` value and an `int` value are the same thing, just a value. – Eric Postpischil Apr 28 '22 at 14:06
  • Potential duplicate: [Purpose of returning by const value?](https://stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value), although I'm not 100% sure how this translates to conversion operators. – Yksisarvinen Apr 28 '22 at 14:09

1 Answers1

5

it will be ignored by compiler.

This is because of expr#6 which states:

If a prvalue initially has the type cv T, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T 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*, ...

Jason
  • 36,170
  • 5
  • 26
  • 60