Use const_cast to modify member variable?

I

Immortal Nephi

How can I modify member variable inside class if member function has
const like mem_Func(void) const. Please do not offer the keyword --
mutable. I want to know if keyword -- const_cast can be done.

If mutable is only the solution, I will follow not to use const_cast.
 
K

Kai-Uwe Bux

Immortal said:
How can I modify member variable inside class if member function has
const like mem_Func(void) const. Please do not offer the keyword --
mutable.

Why not? It's meant to be used for member variables that do not affect
logical constness. If the member variable you are modifying better not be
declared mutable, you probably shouldn't be modifying it in a const member
function.
I want to know if keyword -- const_cast can be done.

Yes it can be used to cast away constness, but it will produce undefined
behavior if you use it on an object declared const.
If mutable is only the solution, I will follow not to use const_cast.

What is the underlying problem that you are trying to solve? I looks as
though you might be headed the wrong direction, and in order to give better
advice some additional information about the background would be good.


Best

Kai-Uwe Bux
 
E

Eric Pruneau

Immortal Nephi said:
How can I modify member variable inside class if member function has
const like mem_Func(void) const. Please do not offer the keyword --
mutable. I want to know if keyword -- const_cast can be done.

If mutable is only the solution, I will follow not to use const_cast.

Ok it is Evil but you can do it.

struct EvilClass
{
void EvilFunct() const;
int _a;
};

void EvilClass::EvilFunct() const
{
int& tmp = const_cast<int&>(_a);
tmp = 5; // now _a == 5
}


You can also define a template function if you have many variables like
that.

struct EvilClass
{
void EvilFunct() const;

template<typename T>
void EvilSet(T const& val, T const& NewVal) const;

int _a;
};

void EvilClass::EvilFunct() const
{
EvilSet(_a, 5); // much cleaner but maybe also much evil
}

template<typename T>
void EvilClass::EvilSet(T const& val, T const& NewVal) const
{
T& tmp = const_cast<T&>(val);
tmp = NewVal;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top