Date: Mon, 16 Dec 2024 08:07:47 +0300
In C++, it’s common to encounter situations where a member variable needs
to be fully controlled by its owner class but also readable from outside
the class. The typical solution is to define a public getter for the
variable:
```cpp
class Foo
{
int value = 0;
public:
int get_value() const { return value; }
};
```
I propose two new access specifiers to make this process easier. First one
is "exposed private". Member variables defined after this specifier would
allow anyone to access these variables as const, but only owner class to
modify them.
The other specifier is "exposed protected", it's the same as before, but
also allows derived classes to modify these variables.
So previous code could just be rewritten as following:
```cpp
class Foo
{
exposed private:
int value = 0;
};
```
It's less boilerplate and you get to refer to the variable with its
original name.
```cpp
Foo foo;
int value = foo.value; // ok
foo.value = 15; // error, can't modify const variable
```
Note: I'm not sure about naming and I'm open to ideas. Also the exact thing
I just specified might contain issues, but you get the idea.
to be fully controlled by its owner class but also readable from outside
the class. The typical solution is to define a public getter for the
variable:
```cpp
class Foo
{
int value = 0;
public:
int get_value() const { return value; }
};
```
I propose two new access specifiers to make this process easier. First one
is "exposed private". Member variables defined after this specifier would
allow anyone to access these variables as const, but only owner class to
modify them.
The other specifier is "exposed protected", it's the same as before, but
also allows derived classes to modify these variables.
So previous code could just be rewritten as following:
```cpp
class Foo
{
exposed private:
int value = 0;
};
```
It's less boilerplate and you get to refer to the variable with its
original name.
```cpp
Foo foo;
int value = foo.value; // ok
foo.value = 15; // error, can't modify const variable
```
Note: I'm not sure about naming and I'm open to ideas. Also the exact thing
I just specified might contain issues, but you get the idea.
Received on 2024-12-16 05:08:01