Click to See Complete Forum and Search --> : Code seems correct but doesn't work


JohnSmith70
May 25th, 2008, 06:43 PM
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:


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

Lindley
May 25th, 2008, 07:23 PM
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.

JohnSmith70
May 25th, 2008, 07:38 PM
Thanks for the reply.

I tried what you said, but now the program keeps crashing. Why?

Philip Nicoletti
May 25th, 2008, 07:58 PM
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:


Trainee * t = new Trainee;
cin >> *t;
obj1.push_back(t);

Lindley
May 25th, 2008, 08:24 PM
Alternatively, if Trainee objects can be copied by value, just make it a list<Trainee> instead.