A const member function

A const member function can be invoked for both const and non-const objects, but a non-const member function can only be invoked for non-const objects.

class Point
{
private:
    int x_;
    int y_;

public:
    Point() : x_{0}, y_{0} {}

    Point(int xin, int yin) : x_{xin}, y_{yin} {}

    // 'elegant' setters
    void x(int xin) { x_ = xin; }
    void y(int yin) { y_ = yin; }

    // 'elegant' getters
    // ### const Member Functions (text excerpted from: Scott Meyers, "Effective C++ (2005)", Itens 3)
    // The purpose of 'const' on member functions is to identify which member functions may be invoked on `const objects`
    // These functions cannot modify an object (its member data).
    // They are important for two reasons:
    // 1. It is important to know which functions may modify an object and which may not.
    // 2. They make it possible to work with 'const' objects, which is a critical aspect in effective C++ code
    // when passing objects by reference-to-const. This technique is viable only if there are `const member functions`
    // with which to manipulate the resulting const-qualified objects.

    // Rule of Thumb: for any member function that does not modify the object, USE const.
    int x() const { return x_; }
    int y() const { return y_; }

    void print() const
    {
        cout << "x, y = " << x_ << ", " << y_ << endl;
    }
};

void foo(const Point &p)
{
    cout << "foo(const Point& p)\n";
    cout << "x, y = " << p.x() << ", " << p.y() << endl
         << endl;
}

// These functions cannot modify an object (its member data).
// They are important for two reasons:
// 1. It is important to know which functions may modify an object and which may not.
// 2. They make it possible to work with ‘const’ objects, which is a critical aspect in effective C++ code

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-17 22:50:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-17 22:50:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-17 22:50:01       58 阅读
  4. Python语言-面向对象

    2024-07-17 22:50:01       69 阅读

热门阅读

  1. 代码随想录算法训练营第14天/优先掌握递归

    2024-07-17 22:50:01       23 阅读
  2. ES6函数部分和数组部分的小练习

    2024-07-17 22:50:01       20 阅读
  3. 学习笔记(数据库)1

    2024-07-17 22:50:01       17 阅读
  4. 后端实现图片上传本地,可采用url查看图片

    2024-07-17 22:50:01       21 阅读
  5. 总览

    总览

    2024-07-17 22:50:01      18 阅读
  6. C4D S26新功能完整列表

    2024-07-17 22:50:01       25 阅读
  7. 大模型日报 2024-07-17

    2024-07-17 22:50:01       25 阅读
  8. 卡码网语言基础课 | 5. A+B问题⑤

    2024-07-17 22:50:01       23 阅读
  9. Web前端-Web开发CSS基础2-选择器

    2024-07-17 22:50:01       17 阅读
  10. 448. 找到所有数组中消失的数字

    2024-07-17 22:50:01       20 阅读
  11. 洛谷P1255 数楼梯

    2024-07-17 22:50:01       20 阅读
  12. C#后台向某个网站发送Get或者Post请求

    2024-07-17 22:50:01       26 阅读