vendredi 10 septembre 2021

Why vector push_back call twice in C++?

In the following program, I have created 3 object of class Person and pushed that object into vector container. After that, the display function is called using a range based for loop and printing the name and age.

#include <iostream>
#include <vector>
#include <iterator>
#include <functional>
 
using namespace std; 

class Person
{
    private:
        string _name;
        int _age;
        
    public:
    
    Person()
    {
    
    }

    Person(string name, int age) : _name(name), _age(age)
    {
        
    }

    void Display()
    {
        cout<<"_name : "<<_name<<" => "<<"_age : "<<_age<<endl;
    }
};

int main()
{
    Person p1("User1", 20);
    Person p2("User2", 30);
    Person p3("User3", 25);
    
    vector<Person> per(3);
    
    per.push_back(p1);
    per.push_back(p2);
    per.push_back(p3);
    
    for(auto obj : per)
    {
        obj.Display();
    }
}

But I don't understad what am I missing here to get output

_name :  => _age : -1
_name :  => _age : -1
_name :  => _age : -1
_name : User1 => _age : 20
_name : User2 => _age : 30
_name : User3 => _age : 25

instead of

_name : User1 => _age : 20
_name : User2 => _age : 30
_name : User3 => _age : 25

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire