Reputation: 97
I have class Person and create a Person type vector. I wanna know hat happens when I call a Person type function with index of vector. Does this store an object in array or what Please explain briefly thanks a lot in advance.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Person
{
int age;
string name;
public:
Person(){};
void getdata()
{
cout << "Enter your name: ";
getline(cin >> ws, name);
cout << "Enter your age: ";
cin >> age;
}
void showdata()
{
cout << "\nHello " << name << " your age is " << age;
}
};
void main()
{
vector<Person> myVector(3);
unsigned int i = 0;
for (i; i < 3; i++)
myVector[i].getdata();//Does this create & save an objects in that location Please explain briefly, Thanks
for (i=0; i < 3; i++) //What if I do this like
/*for (i=0; i < 3; i++)
{ Person p;
myVector.puskback(p); }
or what if I want a new data then what??*/
myVector[i].showdata();
system("pause");
}
Upvotes: 0
Views: 92
Reputation: 1255
Consider
class A
{
public:
A(){}
foo(){}
};
...
int main()
{
std::vector<A> v1(3);
//this creates a vector with 3 As by calling the empty constructor on each
//means means you can readily manipulate these 3 As in v1
for(int i = 0; i < v1.size(); i++)
v1[i].foo();
std::vector<A> v2;
//this creates a vector of As with no pre-instantiated As
//you have to create As to add to the vector
A a1;
v2.push_back(a1);
//you can now manipulate a1 in v2
v2[0].foo();
//You can add to v1 after having initially created it with 3 As
A a2;
v1.push_back(a2);
//You have all the flexibility you need.
}
Upvotes: 1
Reputation: 62553
No, it does not create the object. All objects were created when your vector was created. What it does, it calls getdata() on already constructed object. You can do pushback the way you suggested, and in this case you would like to create an empty vector initially (right now you are creating a vector with 3 elements)
Upvotes: 4