AR-47
AR-47

Reputation: 23

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

Upvotes: 2

Views: 92

Answers (2)

Topological Sort
Topological Sort

Reputation: 2865

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.

Upvotes: 2

the busybee
the busybee

Reputation: 12673

The book was written when the standard C++11 was current. You are compiling with a newer version of the standard, which does not allow this.

Upvotes: 1

Related Questions