Code seems correct but doesn't work
I call this method and pass the list as an argument, but the list doesn't change. Why doesn't it work? I have declared the classes Person and Trainer which work fine. There is something wrong here:
Code:
void read_people(list<Person *> obj1) {
char input;
while (cin >> input)
if (input== ’t’) {
Trainee t;
cin >> t;
obj1.push_back(&t);
}
else if (input == ’ts’) {
Trainer ts;
cin >> ts;
obj1.push_back(&ts);
}
}
Thanx,
John
Re: Code seems correct but doesn't work
You're passing the list by value. It gets copied when the function is called, the copy is modified, and then the copy is discarded when the function returns without the original ever being changed.
Call by reference instead.
Oh, and " input == ’ts’ " makes no sense. Chars can't have more than one character.
Re: Code seems correct but doesn't work
Thanks for the reply.
I tried what you said, but now the program keeps crashing. Why?
Re: Code seems correct but doesn't work
Quote:
Originally Posted by JohnSmith70
Code:
void read_people(list<Person *> obj1) {
char input;
while (cin >> input)
if (input== ’t’) {
Trainee t;
cin >> t;
obj1.push_back(&t);
}
else if (input == ’ts’) {
Trainer ts;
cin >> ts;
obj1.push_back(&ts);
}
}
basically, you are pushing the address of a local variable onto the
list. Once the variable goes out of scope, the adresss in the list
is no longer valid.
You should use new to create the variable on the free store (and
you will need to delete when done). Example:
Code:
Trainee * t = new Trainee;
cin >> *t;
obj1.push_back(t);
Re: Code seems correct but doesn't work
Alternatively, if Trainee objects can be copied by value, just make it a list<Trainee> instead.