Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
Drew Noakes Avatar asked May 16 '11 16:05

Drew Noakes


People also ask

What is equivalent to classes in C?

There is nothing equivalent to classes . Its a totally different paradigm. You can use structures in C. Have to code accordingly to make structures do the job.

What is the C equivalent of CIN?

Standard Input Stream (cin) in C++ It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment. It is generally assumed to be input from an external source, such as the keyboard or a file.

What does &= mean in C?

It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.

What is the equivalent of new in C?

There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.


3 Answers

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

like image 73
jackrabbit Avatar answered Oct 22 '22 10:10

jackrabbit


class Foo
{
private:
    const string _foo;
public:
    Foo() : _foo("Unchangeable")
    {
    }
    void ChangeIt()
    {
        _foo = "Darn";        // compiler error
    }
};
like image 20
Mark Ransom Avatar answered Oct 22 '22 08:10

Mark Ransom


There is no such thing directly. You can use a private field with a public getter (but no setter). But that would only apply to other classes calling your code. Foo always has full acces to its members. But since you are the implementer of Foo, this is no real problem.

like image 40
Christian Rau Avatar answered Oct 22 '22 08:10

Christian Rau