This is a follow up question to my earlier question concerning returning references in C++: Best way to return an object in c++?
I can successfully return a reference, however, I am unable to prevent an observer to completely overwrite the variable in question. I have used const
references, but I want an observer to be able to alter values.
Code below:
class Layer {
public:
Channel& getChannel();
private:
Channel channel;
};
// return reference to channel
Channel& Layer::getChannel() {
return channel;
};
// FINE
layer.getChannel().someMethod();
// BAD: PRIVATE MEMBER IS OVERWRITTEN
layer.getChannel() = Channel();
Now I'm pretty sure to prevent this I have to alter the signature of the function to return a const
reference, however, I'm unable to call someMethod
afterwards:
// CHANGE TO CONST REFERENCE
Channel const& Layer::getChannel() {
return channel;
};
// return const ref of channel
Channel const& channel = layer.getChannel();
// ERROR!!
// 'Channel::someMethod' : cannot convert 'this' pointer from 'const Channel' to 'Channel &'
channel.someMethod();
What's the correct way to write this — and is there a way to prevent overwriting of a private variable?