Class variables: public access read-only, but private access read/write
Of course you can:
class MyClass
{
int x_;
public:
int x() const { return x_; }
};
If you don't want to make a copy (for integers, there is no overhead), do the following:
class MyClass
{
std::vector<double> v_;
public:
decltype(v)& v() const { return v_; }
};
or with C++98:
class MyClass
{
std::vector<double> v_;
public:
const std::vector<double>& v() const { return v_; }
};
This does not make any copy. It returns a reference to const.
While I think a getter function that returns const T&
is the better solution, you can have almost precisely the syntax you asked for:
class myClass {
private:
int x_; // Note: different name than public, read-only interface
public:
void f() {
x_ = 10; // Note use of private var
}
const int& x;
myClass() : x_(42), x(x_) {} // must have constructor to initialize reference
};
int main() {
myClass temp;
// temp.x is const, so ...
cout << temp.x << endl; // works
// temp.x = 57; // fails
}
EDIT: With a proxy class, you can get precisely the syntax you asked for:
class myClass {
public:
template <class T>
class proxy {
friend class myClass;
private:
T data;
T operator=(const T& arg) { data = arg; return data; }
public:
operator const T&() const { return data; }
};
proxy<int> x;
// proxy<std::vector<double> > y;
public:
void f() {
x = 10; // Note use of private var
}
};
temp.x
appears to be a read-write int
in the class, but a read-only int
in main
.