Search code examples
c++ooppropertiesreferencedesign-principles

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';

Solution

  • Generally, it is not a good practice.

    imho, and very easy and clean in class usage code.

    Why should that be clearer and easier?

    • You introduce another variable member (useless overhead). (Generally, the reference will be implemented as an additional member pointer).
    • It makes the code harder to maintain. You are actually creating dependencies among variable members.
    • It makes problem in the assignment and in the copy operations. How is copy operation supposed to work?

    The "classic" approach is sound clearer by me, e.g.:

    class Foo {
     public:
      void set_num(int value) noexcept { m_num = value; }
      int get_num() const noexcept { return m_num; }
      void set_string(std::string value) noexcept {
          m_str = std::move(value);
      }
      const std::string& get_string() const noexcept {
          return m_str;
      }
     private:
      int m_num;
      std::string m_str;
    };
    

    From a performances point of view, this approach should be preferred.

    • Timing complexity: call get_variable on an inline function does not introduce more overhead than your "reference approach". Moreover, it is highly optimizable by the compiler (because of straightforward of the code).
    • Space complexity: it does not introduce additional data member.