Non-overridable reference getter [duplicate]

18 hours ago 2
ARTICLE AD BOX

Suppose there is a class A:

class A { public: int i = 0; };

And class B (holds an instance of class A):

class B { private: A _a; public: A &getA(); // getter };

In class B, how can I return a non-const reference to _a without copying, so that I can modify members of _a, but not allow overrings of _a. I want to allow this:

B b; b.getA().i = 1; // 1. WANTED behavior (allows member modification)

But prevent this:

A otherA; b.getA() = otherA; // 2. UNWANTED behavior (prevents copy assignment)

Running example: https://godbolt.org/z/h1oadnfMs

Natan Camargos's user avatar

2

Read Entire Article