Passing around objects in c++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zensunni
    New Member
    • May 2007
    • 101

    Passing around objects in c++

    So, basically, this is what the classes would look like:

    class Item {
    std::string name;
    }

    class PostOffice {
    std::vector<Ite m> mail;
    }

    class House {
    std::vector<Ite m> mail;
    }


    I'd like to be able to do this in my main:

    PostOffice dhl;
    dhl.sendToHouse ();

    And after the sendToHouse() function is called, the items from the PostOffice object's vector would be transfered to the House object's vector. Is that possible without pointers?
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Yes, it's possible by passing the postoffice's vector as a parameter to the method when you call it, then assigning the contents to the other vector, though using a vector of pointers would speed your program up dramatically as fewer copy constructors and extra copies need to be generated, though you'd have to be careful to avoid segfaults.

    Comment

    • zensunni
      New Member
      • May 2007
      • 101

      #3
      passing the postoffice's vector as a parameter
      do you mean something like this:

      Code:
      void PostOffice::mailToHouse(Vector<Item> &items, int i) {
           PO_member_vector.push_back(items.at(i));
           items.erase(i)
      }
      Or, am I off track? I'm just new to c++, so there might be some things I'm not crystal clear about.

      [edit] wait, that code doesn't work at all. I'll re-do it and edit my post later on..

      Comment

      • Laharl
        Recognized Expert Contributor
        • Sep 2007
        • 849

        #4
        That works for one item, yes. To send all of them, you'd need to use a loop of some kind, be it a for loop with [] or a while loop with iterators (or even a for loop with iterators). Of course, you could put the loop in where you call this and send each item individualy if you want.

        Comment

        Working...