5.9.  Overloading on const

[ fromfile: constoverloading.xml id: constoverloading ]

const changes the signature of a member function. This means that functions can be overloaded on const-ness. Example 5.16 is an example of a homemade vector class with member functions overloaded in this way.

Example 5.16. src/const/overload/constoverload.h

#ifndef CONSTOVERLOAD_H
#define CONSTOVERLOAD_H
#include <iostream>
class Point3 {                                  1
 public:
    friend std::ostream& operator<<(std::ostream& out, const Point3& v);
    Point3(double x = 0, double y = 0, double z = 0);
    double& operator[](int index);    
    const double& operator[](int index) const;  2
    Point3 operator+(const Point3& v) const;
    Point3 operator-(const Point3& v) const;
    Point3 operator*(double s) const;           3
 private:
    static const int cm_Dim = 3;
    double m_Coord[cm_Dim];
};
#endif

1

3-dimension point (of double).

2

Overloaded on const-ness.

3

Scalar multiplication.


The operator function definitions are shown in Example 5.17.

Example 5.17. src/const/overload/constoverload.cpp

[ . . . . ]
const double& Point3::operator[](int index) const {
    if ((index >= 0) && (index < cm_Dim))
        return m_Coord[index];
    else
        return zero(index);
}

double& Point3::operator[](int index) {
    if ((index >= 0) && (index < cm_Dim))
        return m_Coord[index];
    else
        return zero(index);
 }
 
[ . . . . ]

The fact that the two function bodies are identical is worth pondering. If index is in range, each function returns m_Coord[index] - so what is the difference between them? It is important to understand that the non-const version of this operator behaves very much like the function maxi() in Example 5.15.