-
May 25th, 2008, 06:43 PM
#1
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
-
May 25th, 2008, 07:23 PM
#2
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.
-
May 25th, 2008, 07:38 PM
#3
Re: Code seems correct but doesn't work
Thanks for the reply.
I tried what you said, but now the program keeps crashing. Why?
Last edited by JohnSmith70; May 25th, 2008 at 07:48 PM.
-
May 25th, 2008, 07:58 PM
#4
Re: Code seems correct but doesn't work
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);
-
May 25th, 2008, 08:24 PM
#5
Re: Code seems correct but doesn't work
Alternatively, if Trainee objects can be copied by value, just make it a list<Trainee> instead.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|