All Courses
OOP: ADVANCED OOP TOPICS

const Members and Functions

const means something should not be modified.

In OOP, const is used with:

  • Const objects.
  • Const data members.
  • Const member functions.
  • Const references.

Const Member Function

A const member function promises not to modify the object's observable state.

Syntax:

returnType functionName() const;

Complete Example

#include <iostream>
#include <string>
using namespace std;

class Book {
private:
    const int id;
    string title;

public:
    Book(int bookId, string bookTitle) : id(bookId), title(bookTitle) {}

    int getId() const {
        return id;
    }

    string getTitle() const {
        return title;
    }

    void setTitle(string newTitle) {
        title = newTitle;
    }
};

int main() {
    const Book book(101, "OOP in C++");

    cout << book.getId() << endl;
    cout << book.getTitle() << endl;

    return 0;
}

What To Notice

book is a const object.

So it can call:

book.getTitle();

because getTitle() is const.

It cannot call:

// book.setTitle("New Title"); // error

because setTitle() is not const and modifies the object.

Const Data Member

A const data member must be initialized in the constructor initializer list.

Book(int bookId, string bookTitle) : id(bookId), title(bookTitle) {}

You cannot assign to id later inside the constructor body.

Viva Answer

A const member function promises not to modify the object and can be called on const objects. A const data member must be initialized using the constructor initializer list and cannot be changed afterward.

Quick Check

  1. Can a const object call a non-const member function?
  2. Where must a const data member be initialized?
  3. What does the const after a member function mean?