0

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;
}
  • 2
    Modifying a constant object leads to *undefined behavior*. This code is bad. – Some programmer dude Jan 26 '23 at 08:54
  • I know'I do it to show that the constexpr doesn't work. if you want see in https://gcc.godbolt.org/z/zoz7KEqqn in the assembly it's still cal the function and I don't change the value. – shar yashuv Giat Jan 26 '23 at 09:00
  • It's the `fun` function and its `const_cast` that does the bad stuff. Just don't do bad stuff in your code. And where did you get this example from? What's the purpose of it? – Some programmer dude Jan 26 '23 at 09:03
  • Like you say at the top, some cubes can be const and some may not be. The code inside `fun` says "This is one cube that is not const, so change the value". And the compiler does, trusting you not to lie. – BoP Jan 26 '23 at 09:38
  • "I know'I do it to show that the constexpr doesn't work." it doesnt work because you broke it. Its like drving your car from a cliff and then complain to the car factory that the air condition doesnt work. Undefined behavior means absolutely no guarantees on what will happen. – 463035818_is_not_an_ai Jan 26 '23 at 09:39
  • `const` (and by extension `constexpr`) is not a mechanism that protects an object by all means from being modified. Its a helper for you as programmer to not accidentally modify something that should not be modified. If you still modify something that you specified to be unmodifiable then your code is contradicting itself. There is no right output for it, it is undefined – 463035818_is_not_an_ai Jan 26 '23 at 09:42
  • The new example works. You don't call `set` so it's not considered. If you try to call `set` then you'll get errors, as expected. – Some programmer dude Jan 26 '23 at 10:57

0 Answers0