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