Search code examples
c++access-modifiers

Class variables: public access read-only, but private access read/write


Whoopee, not working on that socket library for the moment. I'm trying to educate myself a little more in C++.

With classes, is there a way to make a variable read-only to the public, but read+write when accessed privately? e.g. something like this:

class myClass {
    private:
    int x; // this could be any type, hypothetically

    public:
    void f() {
        x = 10; // this is OK
    }
}

int main() {
    myClass temp;

    // I want this, but with private: it's not allowed
    cout << temp.x << endl;


    // this is what I want:

    // this to be allowed
    temp.f(); // this sets x...

    // this to be allowed
    int myint = temp.x;

    // this NOT to be allowed
    temp.x = myint;
}

My question, condensed, is how to allow full access to x from within f() but read-only access from anywhere else, i.e. int newint = temp.x; allowed, but temp.x = 5; not allowed? like a const variable, but writable from f()...

EDIT: I forgot to mention that I plan to be returning a large vector instance, using a getX() function would only make a copy of that and it isn't really optimal. I could return a pointer to it, but that's bad practice iirc.

P.S.: Where would I post if I just want to basically show my knowledge of pointers and ask if it's complete or not? Thanks!


Solution

  • Of course you can:

    class MyClass
    {
        int x_;
    
    public:
        int x() const { return x_; }
    };
    

    If you don't want to make a copy (for integers, there is no overhead), do the following:

    class MyClass
    {
        std::vector<double> v_;
    
    public:
        decltype(v)& v() const { return v_; }
    };
    

    or with C++98:

    class MyClass
    {
        std::vector<double> v_;
    
    public:
        const std::vector<double>& v() const { return v_; }
    };
    

    This does not make any copy. It returns a reference to const.