Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7510397
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T23:13:02+00:00 2026-05-29T23:13:02+00:00

I’d need to write a class with an overloaded operator [] which has different

  • 0

I’d need to write a class with an overloaded operator [] which has different behavior when the operator [] is used to read or write data.
To give a practical example of what I want to achieve, let’s say I have to write the implementation of a class named PhoneBook which can be used in the following way:

PhoneBook phoneBook(999999); // 999999 is the default number which should be
                             // used when calling someone who is not in the phone book

phoneBook["Paul"] = 234657;  // adds Paul's number
phoneBook["John"] = 340156;  // adds John's number

// next line should print Paul's number 234657
cout << "To call Paul dial " << phoneBook["Paul"] << endl;
// next line should print John's number 340156
cout << "To call John dial " << phoneBook["John"] << endl;
// next line should print 999999 because Frank is not in the phone book
cout << "To call Frank dial " << phoneBook["Frank"] << endl;

The problem is in the fact that when using

phoneBook["Frank"]

I don’t want to add an entry in the phone book for Frank, otherwise a solution based on std::map would be easy to implement.

I did not find on the web any standard way to achieve this so
after some thinking I came up with the following solution in which the operator [] returns a “temporary object” named PhoneNumber. PhoneNumber is then used to distinguish between read/write operations:

#include <iostream>
#include <string>
#include <map>

using namespace std;

class PhoneBook{
private:
    map<string, int> data_; // stores phone numbers
    int defaultNumber_; // default number returned when no matching name is found

public:
    PhoneBook(int defaultNumber) :
        defaultNumber_(defaultNumber) {}

    // Searches in the phone book for a name. If the name is found it returns
    // the corresponding number. If the name is not found it returns defaultNumber_
    int read(string name){
        map<string, int>::iterator it = data_.find(name);
        if (it==data_.end()){
            return defaultNumber_;
        } else {
            return it->second;
        }
    }

    // Forwarding function to map operator []. It is not really necessary but it is added for clarity
    int& write(string name){
        return data_[name];
    }

    // Forward declaration of the "temporary object" returned by operator []
    // See declaration below
    class PhoneNumber;

    PhoneNumber operator[](string name){
        return PhoneNumber(this, name);
    }

    class PhoneNumber{
        friend class PhoneBook;
    private:
        PhoneBook* const phoneBook_;
        string name_;

        // Constructors are private so that PhoneNumber can be used only by PhoneBook
        // Default constructor should not be used
        PhoneNumber() :
            phoneBook_(NULL) {}

        PhoneNumber(PhoneBook* phoneBook, string name) :
            phoneBook_(phoneBook), name_(name) {}

    public:
        // conversion to int for read operations
        operator int (){
            return phoneBook_->read(name_);
            }

        // assignment operator for write operations
        const int& operator = (const int& val){
            return phoneBook_->write(name_) = val;
        }
    };
};

int main(){
    PhoneBook phoneBook(999999);

    phoneBook["Paul"] = 234657;
    phoneBook["John"] = 340156;

    cout << "To call Paul dial " << phoneBook["Paul"] << endl;
    cout << "To call John dial " << phoneBook["John"] << endl;
    cout << "To call Frank dial " << phoneBook["Frank"] << endl;

    return 0;
}

The class PhoneBook behaves like I would like and the program prints:

To call Paul dial 234657
To call John dial 340156
To call Frank dial 999999

I would like to ask you some questions:

  1. Is there any better way to obtain a class behaving like the class I coded?
  2. Has the technique I’m using a name so that I can search more info about it?
  3. Do you see any drawback/possible improvement in my solution?

In the library I’m writing, enabling the behavior I obtained for PhoneBook::operator[]
in a similar situation is really important and I would really like to know what you think about my problem.

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T23:13:02+00:00Added an answer on May 29, 2026 at 11:13 pm

    What you propose is the standard solution to this problem. It’s usually
    known as the proxy pattern or proxy idiom, and the helper class that you
    return is called a proxy. (Since it is a nested class, simply calling
    it Proxy is generally sufficient.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I used javascript for loading a picture on my website depending on which small
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to understand how to use SyndicationItem to display feed which is
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
Basically, what I'm trying to create is a page of div tags, each has
I've got a string that has curly quotes in it. I'd like to replace
I need to clean up various Word 'smart' characters in user input, including but
I have a text area in my form which accepts all possible characters from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.