Question Details

No question body available.

Tags

c++ const-cast

Answers (2)

March 22, 2026 Score: 2 Rep: 574 Quality: Low Completeness: 70%

In short, to answer your first quesiton, yes, the const ness is essentially imbued to member variables (see here, in the structs example). The whole object is considered const. If you don't want this to be the case, you can mark one of your members as mutable.

Your second question is answered by the link above. Since the member variable is actually considered const, constcasting away its constness is undefined behavior, in the same way that this is:

const int i = 1; const int& this
guy = i; constcast(thisguy) = 2; // UB
March 22, 2026 Score: 1 Rep: 49,598 Quality: Low Completeness: 50%

I was under the impression that the implementer of the class could do whatever they wanted and that it was merely the case that const objects could only call const functions.

A const object of any class type can only be safely modified inside the constructor of that respective class. In all other circumstances, it is treated as a const object. So, yes casting away constness is indeed undefined behavior.

Here is a more simplified version to clarify this, also note the use of mutable:

struct C
{
   int x;
   mutable int y;
   C()
   {
    x= 4; //this works even for const objects as we're inside ctor 
   }
   void changexy() const 
   {
    // x = 4; //this won't compile because x is not mutable 
    y = 4; //this will compile because y is marked mutable 
   }
};

const C c; //this uses the ctor which can change value of x as well as y int main() { c.changexy(); }