Hi i am trying to understand the explicit casting in C++, and so playing around by creating different examples. Below i am giving an example which i think should be illegal as it changes the value of a const object.
const char t='a';
const char *pc=&t;
char *p = const_cast<char*>(pc);
std::cout<<"Before changing t "<<*pc<<std::endl;
*p='c';
std::cout<<"After channging t: "<<*pc<<std::endl;
After executing the program the value of the object t successfully changes to c as i can see it in the console. My question are as follows:
- Shouldn't this be illegal since the whole point of having a const object is that it cannot be changed.
- What is the need of having this const_cast and it seems to me that it is dangerous in the sense that we are changing the const object.
- Is it perfectly okay to use const_cast like this?Again, if not then when should i use it?
Aucun commentaire:
Enregistrer un commentaire