ProblemsModern C++Read-only access that does not compile
NoviceModern C++

Read-only access that does not compile

Context

A function takes const Text& and just wants to read characters. It does not compile: the only operator[] in the class is non-const, and a const object is not allowed to call it. You need two versions of the operator — the compiler will pick the right one itself.

Task

t[i] does not compile when t is const — the class only has a non-const operator[]. Add a second, const overload of operator[] so const objects can read. Writing through a const object must stay impossible.

Constraints

  • Reading t[i] must work for both Text and const Text
  • Writing t[i] = c must work for a mutable Text
  • Writing through a const Text must NOT compile
  • Do not use const_cast and do not make fields mutable

Before you code

  • How does the compiler choose between two overloads that differ only in a trailing const?
  • What should the const overload return so that assignment through it is rejected?
  • Why is char& the right return type for the non-const overload?

Tests

  • #1Mutable indexing reads and writes
  • #2A const reference can read
  • #3Writing through const does not compile(expects compile error)

Hints

Hint 1

Two methods may share a name and parameters and differ only in a trailing const — that is a legal overload pair.

Hint 2

Think about what the const version returns: if it hands out a plain char&, writing through a const object would still compile.

Editormissing-const-overload.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.