Search code examples
c++constexprconstexpr-function

Stroustrup book constexpr example does not compile in VS C++ 2022


I am trying to reproduce constexpr example from Stroustrup book "The C++ Programming Language" 4th Ed, pp. 265-266. I am using Visual Studio 2022 Community. The code below does not compile, with the message

error C2662: 'Point Point::up(int)': cannot convert 'this' pointer from 'const Point' to 'Point &'
1\>    Conversion loses qualifiers
struct Point {
    int x, y, z;
    constexpr Point up(int d) { return { x,y,z + d }; }
};
    
int main()
{
    constexpr Point p{1, 2};
    p.up(1);//fails here, no problem if constexpr is removed on the line above
    
    return 0;
}

Would be grateful for a diagnosis and explanations


Solution

  • Here's your fix:

           constexpr Point up(int d) const { return { x,y,z + d }; }
    

    Why do we have to add const? Because omitting const suggests that up can change the Point, and since p is constexpr this can't be allowed.

    And of course since up doesn't change anything, it should be const.