I just discovered that a constexpr method can return correctly the value of a class member that changes during execution. My question is, how is this possible if constexpr methods are supposed to be evaluated completely at compile time?
The example below correctly outputs Value: 0 and then Value: 5. Even more, if I change the a.change(5) to something unpredictible for the compiler (such as a.change(atoi(argv[1])) or a.change(rand() % 10 + 1) it still works. Why? Why does it even compile?
#include <iostream>
class A
{
public:
void change(int value) { x = value; }
int get() const { return x; }
constexpr int value() const noexcept { return x; }
private:
int x{0};
};
int main()
{
A a;
std::cout << "Value: " << a.get() << std::endl;
a.change(5);
std::cout << "Value: " << a.get() << std::endl;
}
Thank you in advance