c++constructorconstantsconst-cast

assign non-static const member in class with const_cast


Why can a non-static const member be assigned using const_cast, and when would this be useful?

In the following code, both A and B classes compile and work fine. However, for B, its const member s is not initialized using an initializer list in the constructor, but by removing the const with const_cast and passing it a value by reference. It can also be written as (string&)s = _s;

I don't often see a const_cast on the left side of an assignment, but this one seems to work fine. What are the pros and cons of B's constructor?

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

class A {
public:
    A(const string& _s) : s(_s) {}
    void display() {cout << s << endl;}
private:
    const string s;
};

class B {
public:
    B(const string& _s) {
        const_cast<string&>(s) = _s;
    }
    void display() {cout << s << endl;}
private:
    const string s;
};

int main() {
    A a("abc");
    a.display();
    B b("def");
    b.display();
    return EXIT_SUCCESS;
}

Output:

abc
def

Solution

  • Why can a non-static const member be assigned using const_cast, and when would this be useful?

    Depends on what you mean by "can".

    The program is well-formed because you modify a non-const lvalue.

    The behaviour of the program is undefined because you modify a const object.

    and when would this be useful?

    Modifying a const object can never be useful.

    Casting away const from a reference is sometimes, although rarely, useful which is why const_cast exists. But it is only useful when you have a const reference to a non-const object.

    What are the pros ... of B's constructor?

    None.

    What are the ... cons of B's constructor?

    The behaviour of the program is undefined if B's constructor is called.