CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2007
    Posts
    41

    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

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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.

  3. #3
    Join Date
    Oct 2007
    Posts
    41

    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.

  4. #4
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    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);

  5. #5
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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
  •  





Click Here to Expand Forum to Full Width

Featured