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.
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.
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?