Boost logo

Boost :

Subject: [boost] Read only attributes in C++ (class proposal)
From: Daniel Illescas Romero (elamericano_at_[hidden])
Date: 2016-10-17 05:36:47

Hello, I wanted to make some read only attributes on C++ so I made a class, named ReadOnly. This class will contain an internal private value, only “friend” classes could change this internally.


· A read only object will contains an internal value that can’t be changed outside the class. For example: ReadOnly<string> name = “Daniel”;
To access its value:, if you try: = “other”, it won’t change it’s value because it’s a read only variable; you can change it’s value only inside the class the object is declared, you could change it like: name.value = “whatever”;
· To set a value (outside the class) to a read only attribute you MUST specify a setter function (which can be static and contained inside the class), like:
ReadOnly<int> age {ReadOnly::setAge, 1}; (optionally you can also set a default value to the attribute).

Example of setter function:

static bool setAge(const int& value) {
        return (value > 0 && value <= 150);

So if you you have an object and you want to change its value like this: object.age = 100; it will change its internal value only if the setter function (which is called internally) returns true.

· The idea of doing all of this instead private variables and getters & setters is because this approach is closer to OOP than what is normally used; I mean if you have an object and you want to get an attribute value, what you need to do in most cases is something like: object.getAttribute(), you are calling a function to just take a look at an attribute, that shouldn’t make sense in OOP, that’s why I made all of this.
It’s also similar to how you manage getters and setters in Swift, because they are embedded in the attribute and you don’t need to make other functions. :)

I uploaded the project to github so everyone can take a look: <>

I wanted to know your opinion about the idea of the class and also about the implementation, I’d love to upload it to boost libraries but I want to know people opinion and make the class better.

Thank you!

Boost list run by bdawes at, gregod at, cpdaniel at, john at