Search code examples
c++constantsconst-cast

Originally declared as constant confusion


const_cast is safe only if you're casting a variable that was originally non-const.

Are literals the only data that was originally declared as constant? If not can anyone please give example of originally declared const data scenario?


Solution

  • No, not just literals are originally declared as const. Any object which is declared as const is "originally const".

    const int this_is_a_const_int = 10;
    const std::string this_is_a_const_string = "this is a const string";
    
    std::string this_is_not_a_const_string;
    std::cin >> this_is_not_a_const_string;
    
    const std::string but_this_is = this_is_not_a_const_string;
    

    What's not originally const is when you have a const reference to a non-const object

    int n;
    std::cin >> n;
    
    const int & const_int_ref = n;
    int& int_ref = const_cast<int&>(const_int_ref); // this is safe, because const_int_ref refers to an originally
                                                    // non-const int