Cem Kalyoncu
Cem Kalyoncu

Reputation: 14593

C++ std::map Intristic Type Initialization Using [] Operator

What a title, suppose I have a map like this:

std::map<int, int> m;

and if I write the following

cout<<m[4];

EDIT:
To clarify, in this question I am seeking for standard behavior.

Thanks in advance, Cem

Upvotes: 2

Views: 173

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75130

The value will be what the default constructor for the type creates, because new spots are filled using T(). For int, this is 0. You can see this for yourself:

#include <iostream>

using namespace std;

int main() {
    cout << int() << endl; // prints 0
}

Initializing a type like with empty parentheses like this is called value initialization (see ildjarn's comment below).

Upvotes: 3

Related Questions