Thread: Passing an array of classes

  1. #1
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820

    Passing an array of classes

    Hey guys not really a problem but another one of my is this right questions. I’m working on a space shooter (a lame one for now). I’m trying to clean up my code by passing an array of classes. When I do this, is there a need to pass it by reference or some other form of working with the direct memory address of the class? Because I wrote some test code but when I tried to pass it as a reference I got errors but when I just passed the array itself it seemed to have modified the data. I just want to make sure this is the right way before I implement it in my stupid game
    Here the code for my test class that seems to do what I want without references.
    Code:
    #include <iostream>
    
    class test
    {
      public:
        void setX(int x){xPos = x;}
        int printX(){return xPos;}
      private:
        int xPos;
    };
    
    void function(test move[],int numOfElms);
    
    int main(void)
    {
      test brian[5];
      function(brian,5);
      for(int i = 0; i < 5; i++)
      {
        std::cout<<brian[i].printX();
      }
      std::cin.get();
      return 0;
    }
    
    void function(test move[],int numOfElms)
    {
      for(int i = 0; i < numOfElms; i++)
      {
        move[i].setX(i);
      }
    }
    Output: 0,1,2,3,4
    So it looks to me as its modifying the values in brian not just making a copy of it
    Last edited by prog-bman; 10-04-2004 at 02:48 AM. Reason: Spelling, Grammer and Punctuation
    Woop?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You never need to pass arrays by reference or pointer. You can always modify the contents of a passed array (const issues aside). Arrays are never passed by value.

    If you really want to test the theory further, make a copy constructor which outputs when it is called.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Thanks quzah all I needed to know Makes my life so much easier
    Woop?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing an Array of Strings from VB to a C DLL
    By mr_nice! in forum Windows Programming
    Replies: 9
    Last Post: 03-08-2005, 06:16 AM
  2. Replies: 6
    Last Post: 02-15-2005, 11:20 PM
  3. Passing a double array from main to another function
    By Loctan in forum C++ Programming
    Replies: 2
    Last Post: 01-04-2005, 05:19 PM
  4. Passing my array to function
    By pooty tang in forum C Programming
    Replies: 8
    Last Post: 09-15-2004, 12:19 PM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM