Just want to know if there is a disadvantage of not using const_cast While passing a char* and simply type-casting it as (char *) or both are basically one and same ?
#include <iostream>
#include<conio.h>
using namespace std;
void print(char * str)
{
cout << str << endl;
}
int main ()
{
const char * c = "sample text";
// print( const_cast<char *> (c) ); // This one is advantageous or the below one
print((char *) (c) ); // Does the above one and this are same?
getch();
return 0;
}
Is there some disadvantage of using print((char *) (c) ); over print( const_cast<char *> (c) ); or basically both are same ?
First of all, your
printfunction should take aconst char*parameter instead of justchar*since it does not modify it. This eliminates the need for either cast.As for your question, C++ style casts (i.e.
const_cast,dynamic_cast, etc.) are prefered over C-style casts because they express the intent of the cast and they are easy to search for. If I accidentally use an a variable of typeintinstead ofconst char*, usingconst_castwill result in a compile time error. However if I use a C-style cast it will compile successfully but produce some difficult to diagnose memory issues at runtime.