Search code examples
c++wrapperencapsulationforwarding

Only allow access to an object's members, not the object itself


Given the following class:

class Foo
{
public:

    //...

private:

    Bar mBar;
};

Is it possible to expose the mBar member in such a way that it's members can be accessed, but not the mBar object itself?

The reason is that users should be able to access all of mBar's members but they should not be able to assign another Bar instance to mBar. Bar has a lot of members and it would be cumbersome to write getters/setters and forwarding fuctions for them all. But if mBar is made public one is able to do aFoo.mBar = Bar(/*...*/);which is the only thing that should not be allowed. Deleting Bar's assignment operators is not an option.


Solution

  • if you only want to protect against errors and not Machiavelli, operator-> might help (you might probably want a wrapper instead of directly put it in foo though):

    class Foo
    {
    public:
        //...
        const Bar* operator ->() const { return &mBar; }
        Bar* operator ->() { return &mBar; }
    private:
        Bar mBar;
    };
    

    so

    Foo foo;
    
    foo->bar_member;
    foo.foo_member;
    
    // Machiavelli
    *foo.operator->() = Bar();