Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const reference field as readonly property in C++ class

Is it good to use a const reference field as a readonly getter in C++ classes?

I mean, does this code meet good practices?

class check{
private:
    int _x;
public:
    const int& x = _x;
    void setX(int v){
        _x = v;
    }
};

It is working very much like C# properties, IMHO, and very easy and clean in class usage code:

  check s;
  int i;
  std::cin >> i;
  s.setX(i);
  std::cout << s.x << '\n';
  s.setX(7);
  // s.x = i; // Error
  std::cout<<s.x<<'\n';
like image 938
Angelicos Phosphoros Avatar asked Sep 18 '17 08:09

Angelicos Phosphoros


People also ask

What is a readonly property c#?

The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.

Can you modify const reference?

But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.

Is const reference type?

Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.

What does const reference do?

- const references allow you to specify that the data referred to won't be changed. A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const.


1 Answers

do this code meet good practices?

Not really, since it introduces unnecessary complexity and space overhead.

Moreover, you wouldn't be able to perform runtime checks and/or assertions, regardless of the value being accessed.

Furthermore, what happens with the lifetime and semantics?

Try assigning one check in your code to another and see what happens. The assignment is ill-formed because the class is non-assignable. You should provide a copy and move constructor to take care of the reference, so that it won't refer to the old object's data member.

Better use _x directly and have a straightforward inline getter function.


PS: C#-like properties in native C++?

like image 59
gsamaras Avatar answered Oct 04 '22 12:10

gsamaras