#include<iostream>
using namespace std;
class temp
{
int value1;
public :
void fun() const
{
((temp*)this)->value1 = 10;
}
void print()
{
cout<<value1<<endl;
}
};
int main()
{
temp t;
t.fun();
t.print();
}
You shouldn't modify a const variable. The whole point of having a const variable is to be not able to modify it. If you want a variable which you should be able to modify, simply don't add a const qualifier on it. Any code which modify's a const forcibly through (pointer)hackery invokes Undefined Behavior.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
So the const only means that the declared function can not be renamed, nor can the parameters be changed.
Because you're casting away const
...
When you cast something, the responsibility is yours for making sure that it doesn't do something dumb.
Note that if temp t;
is changed to const temp t;
, you get undefined behavior, for modifying a const
value.
Coincidentally I literally just touched on this in my blog. (Almost the same function, too.)
$5.4/5 is about explicit type conversion
(which is what is being used here)
The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion. The same semantic restrictions and behaviors apply. If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed. If a conversion can be interpreted in more than one way as a static_cast followed by a const_cast, the conversion is ill-formed.
In this case, ((temp*)this)
got treated as (const_cast<temp *>(this))
and was well-formed. This removed away the constness, thereby allowing to change the class member value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With