how to make a field of a constexpr object constexpr too?

63 Views Asked by At

cube is a class that from what i know can be both constexpr and not and for some reason c.get() is not constexpr because the second cout prints 5 which mean it changed the value of c to 5 instead of c.get() always returning 1.

class cube
{
private:
    int roll;
public:
    constexpr cube(const int& r) :roll(r) {}
    void set(int const& a) { roll = a; }
    constexpr int get() const { return roll; }

    constexpr void fun() const
    {
        (const_cast <cube*> (this))->roll = 5;
    }
};

int main()
{
    constexpr cube c(1);
    std::cout << "Old roll number: " << c.get() << std::endl;
    c.fun();
    std::cout << "New roll number: " << c.get() << std::endl;
    return 0;
}

EDIT: in the comments some said that the fun() breaks it but here it's still not constexpr as you can see here gcc.godbolt.org/z/zoz7KEqqn

#include<iostream>
class cube
{
private:
    int roll;
public:
    constexpr cube(const int& r) :roll(r) {}
    void set(int const& a) { roll = a; }
    constexpr int get() const { return roll; }
};

int main()
{
    constexpr cube c(1);
    std::cout << "Old roll number: " << c.get() << std::endl;
    std::cout << "New roll number: " << c.get() << std::endl;
    return 0;
}
0

There are 0 best solutions below