Course Materials

OOP - Week 4, Lecture 1: Const

Calling a Function on a Const Reference

In Week 3, Lecture 1 we passed an object by const reference, and we hit a limit. We could read other.width, but we could not call other.area():

bool isLargerThan(const Rectangle& other) {
    return area() > other.area();          // error: area() is not marked const
}

Here is why. The parameter is const, which is a promise that the function will not change other. The compiler checks that promise. When you call other.area(), the compiler has to be sure that area() does not change the object. It cannot know that from the call, so it refuses, unless the class says so by marking the function const.

In this lecture we use const in three places: on member functions, on objects, and on data members.

1. Const Member Functions

A const member function is a function that promises not to change the object it is called on. Write const after the parameter list:

int area() const {
    return width * height;
}

Now the compiler allows other.area() on a const reference. The function isLargerThan is the same as before:

bool isLargerThan(const Rectangle& other) {
    return area() > other.area();          // works: area() is const now
}

isLargerThan only reads the two rectangles too, so it should be a const function as well:

class Rectangle {
public:
    bool isLargerThan(const Rectangle& other) const {
        return area() > other.area();      // both area() calls are const
    }
};

The compiler checks the promise inside the function:

  • A const member function cannot change a data member. width = 5; inside area() const is an error.
  • A const member function cannot call a non-const member function, because that function might change the object.
void print() const {
    cout << width << " x " << height << endl;     // reading is fine
    // width = 5;                                  // error: print() is const
    // setWidth(5);                                // error: setWidth() is not const
}

Make a function const when it only reads the object: getters, print(), area(), comparisons. Do not make a function const when it changes the object, such as a setter.

Functionconst?
getWidth(), getHeight()yes: they only read
area(), print()yes: they only read
isLargerThan(const Rectangle& other)yes: it only reads both objects
setWidth(int w)no: it changes width

When the class is split into a header and a source file, write const in both places, as in int area() const; in Rectangle.h and int Rectangle::area() const { ... } in Rectangle.cpp. If one of them is missing, the compiler reports that the definition does not match any declaration.

2. Const Objects

An object can be declared const too. It cannot change after it is created:

const Rectangle r2(2, 2, 5);

r2.print();                  // works: print() is const
r2.getWidth();               // works: getWidth() is const
r2.setWidth(10);             // error: setWidth() is not const

A const object can call only const member functions (static functions are different, see Lecture 2). This is the same rule as for a const reference, and it is the reason why other.area() failed at the start of this lecture: other was a const reference, so it could call only const functions.

Which functions can be called, depending on the object:

The objectConst functions (r.print();)Non-const functions (r.setWidth(10);)
a const object or a const referenceyesno: error
a normal objectyesyes

A normal object can call both kinds.

A const object is still created and destroyed normally: the constructor and the destructor run on it, even though they are not marked const.

A const reference makes a function safe and fast at the same time. The function can read the object without copying it, and the compiler guarantees that the function cannot change it:

void show(const Rectangle& r) {
    r.print();               // works: print() is const
}

A class whose read-only functions are not marked const is hard to use. A const object or a const reference cannot call them. Mark every function that does not change the object as const.

3. Const Data Members

A data member can be const as well. It gets its value once, when the object is created, and it never changes. This is useful for a value like an id:

class Rectangle {
private:
    const int id;            // a const data member
    int width, height;
    ...
};

A const data member cannot be assigned, so it cannot be given its value in the body of the constructor. It must be set in the member initializer list, from Lecture 2 of Week 2:

Rectangle(int i, int w, int h) : id(i) {   // correct: set in the initializer list
    width = 1;
    height = 1;
    setWidth(w);
    setHeight(h);
}
Rectangle(int i, int w, int h) {
    id = i;                  // error: id is const, it cannot be assigned
}

If a constructor does not initialize a const data member in its initializer list, the compiler reports an error, such as β€œconstructor must explicitly initialize the const member”. The exact words depend on your compiler.

There is no setter for a const data member, because nothing is allowed to change it. A getter is enough, and it is a const function.

4. Putting It Together

This program uses all three: id is a const data member, set in the initializer list. The functions that only read are const. r2 is a const object, so it can call only those functions. isLargerThan calls other.area() on a const reference, and show receives r2 by const reference.

Rectangle with constcode/oop/week-04/const-1
#include <iostream>
using namespace std;

class Rectangle {
private:
    const int id;                               // a const data member
    int width, height;

public:
    Rectangle(int i, int w, int h) : id(i) {    // a const member must be set in the initializer list
        width = 1;
        height = 1;
        setWidth(w);
        setHeight(h);
    }

    void setWidth(int w) {
        if (w < 1)                              // validation
            return;
        width = w;
    }
    void setHeight(int h) {
        if (h < 1)                              // validation
            return;
        height = h;
    }

    int getId() const {
        return id;
    }
    int getWidth() const {
        return width;
    }
    int getHeight() const {
        return height;
    }

    int area() const {
        return width * height;
    }

    void print() const {
        cout << "id " << id << ": " << width << " x " << height << " (area " << area() << ")" << endl;
    }

    bool isLargerThan(const Rectangle& other) const {
        return area() > other.area();           // other.area() works because area() is const
    }
};

void show(const Rectangle& r) {
    r.print();
}

int main() {
    Rectangle r1(1, 4, 3);
    const Rectangle r2(2, 2, 5);                // a const object

    r1.print();                                 // 4 x 3
    r2.print();                                 // 2 x 5

    if (r1.isLargerThan(r2))
        cout << "r1 is larger than r2" << endl;

    r1.setWidth(1);                             // r1 is not const, so it can change
    r1.print();                                 // after setWidth

    show(r2);                                   // r2 is passed by const reference

    return 0;
}
Terminal
g++ main.cpp -o app
./app
Tip: click a line of output to jump to the code that printed it.Output hidden. Try it yourself first.

Click each line of output to see what caused it.