Accessing Characters by Using Bracket Notation

With a standard C-style string, you can use brackets to access individual characters:

char city[40] = "Amsterdam";cout << city[0] << endl; // display the letter A

In C++ the two bracket symbols constitute a single operator, the bracket operator, and you can overload this operator by using a method called operator[](). Typically, a binary C++ operator (one with two operands) puts the operator between the two operands, as in 2 + 5. But the bracket operator places one operand in front of the first bracket and the other operand between the two brackets. Thus, in the expression city[0], city is the first operand, [] is the operator, and 0 is the second operand.

Suppose that opera is a String object:

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.