user1602564
user1602564

Reputation: 59

Creating pair object c++

Why it's not possible to create a pair object in the following way:

pair<int,int> p1 = {0,42}

Upvotes: 3

Views: 11766

Answers (2)

Andriy
Andriy

Reputation: 8604

Initializer list syntax is not allowed in C++03 because std::pair is not an aggregate, therefore the valid way of initializing is a constructor call.

Formal definition from the C++ standard (C++03 8.5.1 §1):

An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

Please read FAQ for a detailed explanation.

Things are changed in C++11 by introduction of std::initializer_list.

Upvotes: 4

ForEveR
ForEveR

Reputation: 55887

in C++03 you should use

std::make_pair(0, 42);

since pair is not simple data-structure. or by calling constructor of pair i.e.

std::pair<int, int> p1(0, 42);

in C++11

pair<int, int> p1 = {0, 42}

is okay.

Upvotes: 10

Related Questions