devxlogo

Overload Operator []

Overload Operator []

Question:

Is it possible to overload the ‘subscripting operator’ [] so it will take char * as the index, similar to an array?

For example:

I want to write a class which will store ‘name’ and ‘age’.

class_profile XX["Mary"] = 18;X["Mike"] = 20;X["John"] = 12;

So it will work in such condition.

if ( X["John"] < 18 ) {  cout << "Kid !" << endl;}

Answer:

Actually, C++ already defined such a class, std::map<>. A map is also called an associative array, which is an array whose indices aren't necessarily integers. Thus, you can use a string as the subscript of an associative array.

std::map takes a pair of elements, one is the key and the second is the associated value. In your example, the key can be a string that contains a person name, and the associated value is the person's age. std::map overloads operator [] so you can do something like this:

#include  //for pair<>#include #include #include using namespace std;int main(){pair Person(string"Lee"),23); /*create a pair */map mp; /*create a map*/mp.insert(Person); /*insert pair into map*/int age = mp["john"]; /*age = 23; string used as subscript */return 0;}

There are two steps here: first, you create a pair<> element using the standard class template std::pair (defined in ). The pair contains the name of the person and its associated value, namely the person's age. Then, you insert that pair into a map, and use map's subscript operator to retrieve the person's age by his or her name.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist