Need help involving vectors and classes

I am having trouble putting data from a txt file onto a vector of a class.
For instance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class employee{
setname(string)
{
some code
}
getname ()
{
some code
}
setid(int)
{
some code
}
getid ()
{
some code
}
};
int main()
{
int num = 0;
 vector<employee> vec;

ifstream instream;
instream.open(somefile);

while(!instream.eof())
{
  tempname;
  instream >> tempname;
vec[num].setname(tempname);
  num++;
}

}

How would use my setname function in my class using my vector?
I tried doing vec[num].setname(tempname) but it doesn't work. I know it does not work because I have to use .push back for a vector but I don't know exactly how to pushback using the setname functioncall. Thank you for the help!! Really appreciate it.
you have to create the new vector element first, then call the .setname() member. You can't have the setname() member create the object. that's a chicken and egg problem.
Last edited on
sorry, but what do you mean by "creating the new vector element first"? I don't really understand what that means
how you'd really want to do this is by having a constructor of employee which takes a string argument for the name. once that's implemented, vec.push_back( tempname ); should work.

what you're doing above vec[num].setname( tempname ); will only work to change an existing element's name.
Ahh, I see. Sorry to bother you, but I have another question. Let's say i have more than one constructor that takes a string argument. How would I differentiate between the two?
Say i have 2 constructors
Employee (string firstname)
and
Employee(string lastname).
How would I input my data into separate ones because they both take a single string argument.
Last edited on
You can't really. you could have a constructor take a single string:
Employee( string firstname )

and another constructor which takes two strings:
Employee( string firstname, string lastname )

but can't have two that only take a single string argument. You would have to find some other way to differentiate the number and or type of arguments.
so going back to my original problem, how would I use the setname function without using a constructor since I have multiple functions using only one string as a parameter?
something like this should work
1
2
3
4
5
6
7
8
while(!instream.eof())
{
	tempname;
	instream >> tempname;
	
	vec.push_back(); // create new element
	vec[vec.size() - 1].setname(tempname);
}
for vec.push_back() you need an argument. It doesn't work if I compile it as is
oh yeah... try this.
vec.push_back( employee temp );

just creates a new empty employee object to pass.
yea, same issue. Doesn't compile correctly
Topic archived. No new replies allowed.