What is the C++ equivalent of C#'s readonly field modifier?

Drew Noakes picture Drew Noakes · May 16, 2011 · Viewed 18.7k times · Source

Locking down state is great. In C# you can ensure that a field doesn't change it's value/reference once the constructor completes by declaring it as readonly.

class Foo
{
    private readonly string _foo;

    public Foo() {
        _foo = "Unchangeable";
    }

    public void ChangeIt() {
        _foo = "Darn";        // compiler error
    }
}

Can I do the same thing with C++? If so, how? If not, why not?

Answer

jackrabbit picture jackrabbit · May 16, 2011

That would be const. Note that this keyword means a couple of different things in different contexts.