const_cast conversion

From Cppreference

Jump to: navigation, search

Converts between types when no implicit conversion exists.

Contents

[edit] Syntax

const_cast < new_type > ( expression )

All expressions return an value of type new_type.

[edit] Explanation

All above conversion operators compute the value of expression, convert it to type and return the resulting value. Each conversion can take place only in specific circumstances or the program is ill formed.

Casts type to an equivalent type with different cv-qualifiers.

[edit] Keywords

const_cast

[edit] Example 1

#include <iostream>
 
int main() 
{
    int i = 3;
    const int& cref_i = i;
    const_cast<int&>(cref_i) = 4;
    std::cout << "i = " << i << '\n';
}

Output:

i = 4

[edit] Example 2

#include <iostream>
 
struct type {
    type()
       :i(3)
    {}
 
    void m1(int v) const 
    {
    // this->i = v; // compile error: assignment of member 'type::i' in read-only object
        const_cast<type*>(this)->i = v;
    }
 
    int i;
};
 
int main() 
{
    type t;
    t.m1(4);
 
    std::cout << "type::i = " << t.i << '\n';
}

Output:

type::i = 4

[edit] See also