2

I am reading Programming Principles and Practice Using C++ written by Bjarne Stroustrup, and I am stuck at page 204, about constexpr, seems like I cannot make the code example in the book compile:

constexpr double xscale = 10;
constexpr double yscale = 0.8;
constexpr Point scalePoint(Point p)
{
    return{ xscale * p.x, yscale * p.y };
}

Point is a class with two members, x y, and a constructor:

class Point
{
    double x;
    double y;
    Point(double inX, double inY)
        : x(inX),y(inY)
    {

    } 
};

The error I am getting is:

Error (active)      
function "scalePoint" (declared at line 13) was previously not declared constexpr
4
  • Where do you get the error? Can you please try to create a Minimal, Complete, and Verifiable Example and show us, including how you call the function. Commented Feb 18, 2017 at 21:11
  • 2
    If you are returning a Point, you might want to make the constructor constexpr as well. Commented Feb 18, 2017 at 21:13
  • 2
    The error makes it sound as if you have a prototype of scalePoint somewhere outside the code you posted which is declared without constexpr. Commented Feb 18, 2017 at 21:13
  • 1
    Most compilers will tell you where the previous declaration was. Read on! Commented Feb 18, 2017 at 21:22

1 Answer 1

2

As commenter Bo pointed out correctly, you must make the constructor of Point constexpr too. Constexpr functions can only call other constexpr functions!

In addition, you have only private Members in class Point. So function scalePoint() cannot access p.x, p.y and cannot create an instance of Point as a return value because the constructor is private.

Make Point a struct or add a "public:" statement:

struct Point
{
    double x;
    double y;
    constexpr Point(double inX, double inY)
        : x(inX),y(inY)
    {

    } 
};

That compiles for me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.