M
mailtogops
Hi,
I often think over the const_cast operator provided by C++ and I feel
usage of const_cast or the document availale for const_cast are
cumbersome.
C++ provides us, const qualifier which force a variable or an object
remain constant throughout lifetime of the program.
class Experiment
{
public:
int _member;
public setMember(int i)
{
_member = i;
}
};
void main()
{
const Experiment exp; // const object. I can't do set
}
Here my question is const_cast talks about removing this particular
const_ness of the object exp?
Experiment &e = const_cast<Experiment&> (exp);
e.setMember(10);
In the above code, it doesn't make sense to change the constant object
through the reference after the const_cast.
the code,
void Fun(const Experiment& obj)
{
Experient &rObj = const_cast<Experiement&> (obj);
rObj.setMember(40);
}
void main()
{
// Valid use
Experiment obj; // note not a constant
Fun(obj); // make sense
// Value of the object changed in the Fun
// Invalid use
const Experiment cObj;
Fun(cObj); // non-sense.. Am i right?
// Value of the object cObj should not changed in the Fun
}
So can some one define the what is constness?. How it can be used?
Thanks & Regards,
Gopal
I often think over the const_cast operator provided by C++ and I feel
usage of const_cast or the document availale for const_cast are
cumbersome.
C++ provides us, const qualifier which force a variable or an object
remain constant throughout lifetime of the program.
class Experiment
{
public:
int _member;
public setMember(int i)
{
_member = i;
}
};
void main()
{
const Experiment exp; // const object. I can't do set
}
Here my question is const_cast talks about removing this particular
const_ness of the object exp?
Experiment &e = const_cast<Experiment&> (exp);
e.setMember(10);
In the above code, it doesn't make sense to change the constant object
through the reference after the const_cast.
reference to an object which is not actually a constant object. Look atFrom my understanding, const_cast could be applied to an constant
the code,
void Fun(const Experiment& obj)
{
Experient &rObj = const_cast<Experiement&> (obj);
rObj.setMember(40);
}
void main()
{
// Valid use
Experiment obj; // note not a constant
Fun(obj); // make sense
// Value of the object changed in the Fun
// Invalid use
const Experiment cObj;
Fun(cObj); // non-sense.. Am i right?
// Value of the object cObj should not changed in the Fun
}
So can some one define the what is constness?. How it can be used?
Thanks & Regards,
Gopal