I have a class and I am creating an object of it using parameterized constructor. During this time both parameterized and default constructor has been called.
Here is my snippet:
class student {
string name;
int age;
public:
student() {
cout << "Calling the default constructor\n";
}
student(string name1, int age1) {
cout << "Calling the parameterized const\n";
name = name1;
age = age1;
}
void print() {
cout << " name : " << name << " age : " << age << endl;
}
};
int main()
{
map<int, student> students;
students[0] = student("bob", 25);
students[1] = student("raven", 30);
for (map<int, student>::iterator it = students.begin(); it != students.end(); it++) {
cout << "The key is : " << it->first ;
it->second.print();
}
return 0;
}
When I am executing this snippet, my output is coming as:
Calling the parameterized const
Calling the default constructor
Calling the parameterized const
Calling the default constructor
The key is: 0 name: bob age: 25
The key is: 1 name: raven age: 30
So, I want to understand, if I am calling the parameterized constructor, why default constructor has been called after the parameterized constructor?
Because std::map::operator[]
will insert a default-constructed student
firstly if the specified key doesn't exist. Then the inserted student
gets assigned from the temporary student
like student("bob", 25)
.
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
You can use insert
instead.
students.insert({0, student("bob", 25)});
students.insert({1, student("raven", 30)});
students[0]
is constructing automatically the object using it's default constructor. students[0] =
use the copy assignment operator, and student("bob", 25)
calls the parameterized constructor
.
You can use:
studets.insert(pair<int, student>(0, student("bob", 25)));
or:
studets.emplace(0, student("bob", 25));
To avoid the default constructor.
T& operator[](const key_type& x);
Effects : Equivalent to: return try_emplace(x).first->second;
T& operator[](key_type&& x);
Effects : Equivalent to: return try_emplace(move(x)).first->second;
T& at(const key_type& x); const T& at(const key_type& x) const;
Returns : A reference to the mapped_type corresponding to x in* *this.
Throws : An exception object of type out_of_range if no such element is present.
Complexity : Logarithmic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.