-4

What the difference between up and up1 here?

Why does const work, but not constexpr?

class vec3 {
    int x, y, z;
public:
    vec3(int x, int y, int z) : x{x}, y{y}, z{z} {}
};

int main()
{
    // Error C2127'up': illegal initialization of 'constexpr'
    // entity with a non-constant expression
    constexpr vec3 up{0, 1, 0};

    const vec3 up1{0, 1, 0};
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Y.Lex
  • 241
  • 1
  • 7

1 Answers1

1

If you want to create a constexpr object, then the corresponding constructor needs to be constexpr as well. So, the constructor needs to be like this:

constexpr vec3(int x, int y, int z) : x{x}, y{y}, z{z} {}

(If the initialization of a constexpr object involves calling a function, then the function needs to be constexpr as well. A constructor is not an exception to this rule.)

geza
  • 28,403
  • 6
  • 61
  • 135