I had an idea for a feature for C++, and I was wondering if it was possible to create.
Let's say I want a private variable in 'MyClass' to be accessible only by two functions, the public getter and setter. That is, if another public or private function of MyClass tries to get or change the value of my super-private variable, I will get a compile error. However, the getter and setter behave normally.
Any ideas?
Edit 1: A use case is having the getter/setter perform error checking or other form of logic. I wouldn't want even the class itself touching the variable directly.
Edit 2: Something like this then:
template <class T>
class State{
private:
T state;
public:
State()
{
state = 0;
}
T getState()
{
return state;
}
void setState(T state)
{
this->state = state;
}
};
And then any class can inherit it and access 'state' only through the getter/setter. Of course, the class is useless without modifying the getter and setter according to your desired logic.
I would put a very ugly name to the variable, and a nice one to the getter/setter:
A comment expaining what super-private means will be most welcome by the people that inherits your code.
The granularity of accessibility in C++ is the class.
So if you need to make a variable accessible to only two methods you need to move the variable and the two methods into a separate class, dedicated to maintaining privacy..
I believe this is what you asked for. Is it desirable? Some people will think this is an abomination.
If you decided to use it, you'll probably want to pull out the public Get and Set from the macro and write those manually.
You could wrap the variable in a class and make it private there and a
const T&
getter. Than you declare the get and set member functions of the containing class as friends to that wrapper. Now you keep the wrapper class as a member in your original class. That should achieve what you want albeit it looks hard to maintain and not very useful.So here is some dummy implementation that shows how this would work (Note that the whole
new VeryPrivateWrapper
business is just a wacky way around declarations, aunique_ptr
would be more helpful):