I'm learning c++ and came across this const_cast operator. Consider the following example:
class Test
{
private:
char name[100];
public:
Test(const char* n) { std::strncpy(name, n, 99); name[99]=0; }
const char* getName() const { return name; }
}
Now a user can do
Test t("hi");
const_cast<char*>(t.getName())[0] = 'z'; //modifies private data...
Is this fine ? I mean modifying private data since the purpose of return const char* was to prevent changing private data. How do I prevent this ? (without using std::string)
For safety and simplicity, don't return pointers or references to non-const objects from const methods. Within that constraint, mark methods as const where possible. Avoid const_cast to remove const, except when implementing non-const getters in terms of const getters.
C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function returns a reference or pointer.
const member functions have the following use cases: A const function can be called by either a const or non- const object. Only a non- const object can call a non- const function; a const object cannot call it.
const_cast is one of the type casting operators. It is used to change the constant value of any object or we can say it is used to remove the constant nature of any object. const_cast can be used in programs that have any object with some constant value which need to be changed occasionally at some point.
No this is not 'fine'. Though it is possible. But C++ doesn't force good behavior on programmers. It mainly allows you to declare things in a way that show their intended use. If a programmer decides to trick around that protection he should know what he is doing.
Bjarne Stroustrup: Yes. That's the new cast syntax. Casts do provide an essential service. The new syntax is an improvement over the C-style casts because it allows the compiler to check for errors that it couldn't with the old syntax. But the new syntax was made deliberately ugly, because casting is still an ugly and often unsafe operation.
No, it's not fine, but that's the whole point of const_cast
. Generally, when a programmer overrides const
a whole bunch of bad things may happen, and it is not advised to do that. I'm not sure if you can prevent someone from doing that though, because the point of const_cast
is to override the protection generally provided by const
.
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