C++ doesn't support getter/setter style properties. But you can get pretty darn close with templates or macros.
#include <iostream>
#include "properties.h"
using namespace std;
class User
{
private:
int mId;
int mWeight;
int mPurse;
int mBank;
public:
// Non-auto property only supporting get (runtime check)
Property<int> Id{{ .get = mId }};
Property<int> Purse {{ .set = mPurse }};
Property<int> Bank {{ .set = mBank }};
Property<int> Wealth {{ .get = [this]() { return mPurse + mBank; }}};
// Auto-properties
Property<string> FirstName;
Property<string> LastName;
// Non-auto property
Property<string> FullName {{
.get = [this]() { return LastName + string(", ") + FirstName; }
}};
// Property backed by member variables
Property<int> Weight { mWeight };
// Non-auto property with value checks
Property<int> Age {{
.get = [](int value) { return value; },
.set = [](int& value, int newValue) {
if (newValue < 0) newValue = 0;
if (newValue > 150) newValue = 150;
return value = newValue;
}
}};
User(int id) { mId = id; }
};
int main()
{
auto user = User(0);
cout << "First Name: ";
cin >> user.FirstName;
cout << "Last Name: ";
cin >> user.LastName;
user.Age = 46;
cout << "Full Name: " << user.FullName << endl;
user.Age++;
cout << "Age: " << user.Age << endl;
// user.Id = 10; // Throws an exception
user.Weight = 205;
user.Purse = 20;
user.Bank = 100;
cout << "Wealth: " << user.Wealth;
// user.Wealth = 100; // Throws an exception
}
It's not perfect but it's close.
We can get the above by extending Peter Dimov's Named Parameters in C++20 post and the templating approach for C++ properties on Wikipedia: