I have a class which made of a ints and strings, but I also have a vector inside that class. I have to read the records from a file and then after parsing each line, put the info in my vector of class. I have to get the basic package information like ID and name and then add the services which are offered with that package, so I can have 10 records that are from one package but they are different in type of services. For now I am trying to work out putting the data in each package and access the data from each element, but when I am trying to get the data from the vector inside the class, my compiled file crashes. It also prints out the 1233 and foo, but not the test. Any ideas why is that?
int main()
{
vector<package> packs;
package pack;
pack.ID = 1233;
pack.name = "foo";
packs.push_back(pack);
pack.putData("test",12);
cout << packs[0].name << endl;
cout << packs[0].ID << endl;
cout << packs[0].bservice[0].serviceID << endl; //[b]Crashes in this line[/b]
return 0;
}
Defined class is:
class package
{
public:
class aservice
{
public:
int serviceID;
string othername;
};
int ID;
string name;
vector<aservice> bservice;
void putData(string name1, int serviceID1)
{
aservice obj;
obj.serviceID = serviceID1;
obj.othername = name1;
bservice.push_back(obj);
}
};
Here you make a copy of
packwhen youpush_backinto the vector:And here you access
pack, not the copy stored in your vectorSo the
bservicevector you are trying to access is actually empty, which is why your code crashes when you try to access it here:You can avoid this by pushing back after the call to
putData:You can also avoid it by not trying to access a vector without first checking whether it is empty.
Ideally you should strive to design classes than can be constructed into a useful state, as opposed to default constructing them and adding data step by step via setters. This is particularly important if the data are inter-related and the class must maintain invariants.