5.9.1. Exercises: Overloading on const

  1. In Example 5.18, the compiler can tell the difference between calls to the const and to the non-const versions of operator[] based on the const-ness of the object.

    Example 5.18. src/const/overload/constoverload-client.cpp

    #include "constoverload.h"
    #include <iostream>
    
    int main( ) {
        using namespace std;
        Point3 pt1(1.2, 3.4, 5.6);
        const Point3 pt2(7.8, 9.1, 6.4);
        double d ;
        d = pt2[2];    1
        cout << d << endl;
        d = pt1[0];    2
        cout << d << endl;
        d = pt1[3];    3
        cout << d << endl;
        pt1[2] = 8.7;  4
        cout << pt1 << endl;
        //  pt2[2] = 'd';
        cout << pt2 << endl;
        return 0;
    }
    
    

    1

    __________

    2

    __________

    3

    __________

    4

    __________

    <include src="src/const/overload/constoverload-client.cpp" href="src/const/overload/constoverload-client.cpp" id="constoverloadclientcpp" mode="cpp"/>


    Which operator is called for each of the notes?

     

    1. double operator[](int index) const;

    2. double& operator[](int index);

    3. same as 2.

    4. same as 2.

  2. Why is the last assignment commented out?

      Because only const versions can be called on pt2, and there is no const version that returns a reference.

[ fromfile: constoverloading.xml id: None ]