You could create accessor methods like this:
class Data
{
public:
inline int GetA() const { return a; }
inline int GetB() const { return b; }
inline int GetC() const { return c; }
private:
const int a, b, c;
};
Accessor methods are methods that do not alter the state of the object. They are simply methods used to control access to the data within the object by providing as extra layer of access. This way, the user will not have direct access and will have to go through the accessor methods to access the original data.
To avoid a const_cast
from mutating your read-only data, the easiest way is to hide the memory location of your data, which means that the user must neither be able to get a reference nor a pointer to your data. This essentially means that you're left with providing the user with a copy of your data.
From your example, it seems you're only using int
s, so returning a copy is generally inexpensive. However, imagine if you have a vector
of 1000000 int
s. Attempting to make a copy of that will be considerably expensive (just think about how you would make a copy of an array of 1000000 int
s). In such cases where the size of the data is not trivial, you would want to return a read-only reference to the data instead to prevent any copying like so.
class Data
{
public:
inline const std::array<int, 1000>& GetA() const { return a; }
inline const std::array<int, 1000>& GetB() const { return b; }
inline const std::array<int, 1000>& GetC() const { return c; }
private:
const std::array<int, 1000> a, b, c;
};
So in the end, you'll have to make a judgement call. Is data security more important than performance? If so, hide the data and only return copies of the data. Otherwise, is the data of negligible size? If so, returning a reference might actually be more expensive than simply making a copy of the data, otherwise, return a read-only reference.
Pseudocode:
If security is more important than performance
Return a copy
Otherwise
If size of data is of negligible size
Return a copy
Otherwise
Return a read-only reference