Software & Finance

Visual C++ - const_cast

The object buf holds the string "Test". The object cp is a non constant pointer pointing to constant value. We are going to change the value by doing const_cast. ncp is a non constant pointer pointing to non constant value. ncp is assigned with cp by const_cast. The value is changed using ncp and it directly affects the buf object. Again const char* is converted back to char* pointer using const cast at the last step cncp. cncp is pointing to buf and it is displayed out on the screen.

Source Code


int _tmain(int argc, _TCHAR* argv[])


    char buf[128] = "Test";

    const char *cp = buf;

    char *ncp = const_cast(cp); // Converting const char* to char*


    strcpy(ncp, "non const write successfull\n\n");


    const char *cncp = const_cast(ncp); // Converting char* to const char*


    std::cout << cncp; // cncp is pointing to buf


    return 0;




non const write successfull