How to access methods of classes stored in an unordered_map in C++

So I have a class named Account and I am storing it in an unordered_map, but when I try to access the functions of that class within the map, it fails to compile. The class is stored in a header file "Bank.h"

class Account {
    double balance;
    std::string username;

    public:
    Account(double balance, std::string username);

    double getBal() {
        return this->balance;
    }

    std::string getName() {
        return this->username;
    }

    void updateBal(double amount) {
        this->balance += amount;
    }
};

These functions are stored in a separate cpp file with #include "Bank.h"

std::unordered_map<std::string, Account> accountList;
Account test(100, "Tester");
std::cout << test.getBal();
accountList.insert(std::make_pair("Test", test));
accountList["Test"].getName();

1 answer

  • answered 2021-11-23 01:58 Sam Varshavchik

    accountList["Test"].getName();
    

    The [] operator on an unordered map (and std::map too) has a mandatory requirement that must be met: if the map's key does not exist, it gets created and the corresponding value gets default-constructed.

    Unfortunately, your Account class does not have a default constructor, hence the compilation failure.

    It is true that just before this line of code you are inserting a value for "Test" into the map, so it'll exist. This, unfortunately, does not matter. All requirements of the operator[] must be met, including the map's value requirement to have a default constructor.

    You have two options to resolve your compilation error:

    1. Add a default constructor to your Account class, or

    2. You cannot use [], instead use at(); or use find() (and compare its result to end()).

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum