Thread: array of objects

  1. #1
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312

    array of objects

    I need for my "console-text-based-generals-strategy-game" an array of objects. The size of the array depends on user input. I tried some ideas, but it keeps giving me errors. Should I overload new and delete?

    Code:
    // player class
    
    class player
    {
    public:
      // variables
      int soldiers;
      int tanks;
      int planes;
      int artil;
      int barracks;
      int warfactory;
      int airfield;
      int supctr;
      int supcar;
      
      // methods
      player(string c, int diff, string n);
      ~player();
      string getcountry();
      void setgold(int g);
      string getname();
      int getgold();
      string battle_start(player & p2);
    private:
      string * name;
      string * country;
      int * gold;
    };
    
    
    
    // in the newgame() function
    
    player persons[players];
    
    for(int i = 0; i < players; i++)
    {
      persons[players](country, difficulty, name); // use constructor
    }
    But this does work:

    Code:
    player persons[3] = 
    {
        player(country, difficulty, name),
        player(country2, difficulty, name2),
        player(country3, difficulty3, name3)
    };
    Ideswa
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  2. #2
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300
    Defining an array with a variable size isn't standard, IIRC.

    Have you looked into vectors? Then you could:
    Code:
    cin >> players;
    vector<player> persons;
    for (vector<player>::size_type i = 0; i != players; ++i)
    {
       //determine country, difficulty, name for player i
       player temp(country, difficulty, name);
       persons.push_back(temp);
    }
    to get a container of objects with whatever size you need.
    There is a difference between tedious and difficult.

  3. #3
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    Thanks Decrypt! I know the basic of vectors but I'll go have a look on the vector tutorials of this website.
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    1) Use vectors.

    2) You can't declare an array with a variable for it's size. That's prenatal C++.

    3) You can create arrays 'dynamically', which allows you to set the size at runtime:
    Code:
    #include <iostream>
    using namespace std;
    
    class Apple
    {
    public:
    	Apple()
    	{
    		cout<<"Default contructor called."<<endl;;
    	}
    };
    
    int main()
    {
    	cout<<"How many apples?"<<endl;
    
    	int input;
    	cin>>input;
    
    	Apple* ptr = new Apple[input];
    
    	
    	
    	delete [] ptr;
    
    	return 0;
    }
    Last edited by 7stud; 04-20-2006 at 09:16 AM.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    string * name;
    string * country;
    int * gold;
    Unless you have a real need to do so I'd suggest not making these pointers.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    It was just for practise, those pointers, with constructors/destructors and some getname()/setname() functions. Thanks for the help!

    Edit: That allocating doesn't work with my class?
    Last edited by Ideswa; 04-20-2006 at 11:00 AM. Reason: add a question
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Quote Originally Posted by Ideswa
    It was just for practise, those pointers, with constructors/destructors and some getname()/setname() functions. Thanks for the help!

    Edit: That allocating doesn't work with my class?
    Based on the output of the code I posted, and the text of the error message you get, why do you think that is?

  8. #8
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    Code:
    void newgame()
    {
      int diff;
      int players;
      string win;
      
      cout << "How many players? ";
      while(!(cin >> players))
      {
        cin.clear();
        cin.ignore(1000, '\n');
        cout << "Wrong input, please re-enter: ";
      }
      
      string name[players];
      string ctr[players];
      
      for(int i = 0; i < players; i++)
      {
        cout << "(" << i+1 << "p): Name? ";
        cin >> name[i];
      
        cout << "(" << i+1 << "p): Which country? ";
        cin >> ctr[i];
      }
      
      cout << "Difficulty? ";
      cin >> diff;
      
      vector<player> persons;
      
      for (vector<player>::size_type i = 0; i != players; ++i)
      {
        //determine country, difficulty, name for player i
        player temp(ctr[i], diff, name[i]);
        persons.push_back(temp);
      }
    }
    The last for loop doesn't give me any compiler errors/warnings, but when I run it and when I entered the "Difficulty" I get a microsoft error, you know, with "Do you want to send an error report?".
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  9. #9
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300
    Sounds like you're crashing for going out of bounds again. I think that sort of thing comes from accessing memory you're not allowed to access. Put some debugging output statements in, something like:
    Code:
      cout << "Difficulty? ";
      cin >> diff;
    
    cout << "creating vector of players" << endl;
      
      vector<player> persons;
      
      for (vector<player>::size_type i = 0; i != players; ++i)
      {
        //determine country, difficulty, name for player i <-input all the info here
    cout << "creating player " << i << endl;
        player temp(ctr[i], diff, name[i]);
    cout << "pushing player " << i << " onto the vector" << endl;
        persons.push_back(temp);
      }
    Make sure you use endl and not '\n' to start the new lines there, or it may not be effective. Determine when the crash is actually occuring by watching the output. If you need, put in some cin.get()s so that you can see it step by step. That should better illustrate just where the error is occuring.

    Also, you're still creating an array with a variable defined at run-time. I'd use vectors for the whole deal. The comment I appended in blue above represents where you should input the name, country, and difficulty of each player. Then push the player onto the vector, then the next iteration of the loop will get the next player's information.
    There is a difference between tedious and difficult.

  10. #10
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    The error occurs when player 2 (nr 3) is being "Pushed". I don't know what to do about it.
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  11. #11
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Read point number 2) in my previous post. Then go through your code and delete any lines where you are doing that.

  12. #12
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    Of course! I used memory allocating and the problem was solved. Thanks for all the help!
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  13. #13
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Of course! I used memory allocating and the problem was solved.
    Unfortunately, that is the wrong solution(and I bet you forgot to delete the allocated memory).

    See Decrypt's post and the blue line in his code example for the proper solution.
    Last edited by 7stud; 04-22-2006 at 12:28 PM.

  14. #14
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    I did it like this:

    Code:
    for (int i = 0; i < players; i++)
    {
        cout << "(" << i << "p): Name? ";
        cin >> name;
        cout << "(" << i << "p): Which country? ";
        cin >> ctr;
        
        cout << "Creating player " << i << endl;
        Sleep(1000);
        player temp(ctr, diff, name);
        cout << "Pushing player " << i << endl;
        Sleep(1000);
        persons.push_back(temp);
        cout << "Player " << i << " ready." << endl;
        Sleep(1000);
        cin.clear();
        cin.ignore(1000, '\n');
        name = "";
        ctr = "";
    }
    But if I enter 3 players, the third player crashes after it couts "Pushing player i". It can't be out of bounds, because arrays aren't used. What can I do?
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  15. #15
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    There's a lot of missing code you aren't posting.

    However, you need to create some practice code to play with until you figure out how to use vectors. To wit, create a class with two member variables and a constructor that initializes those variables. Then write a for loop that gets user input for the two variables, creates the object, and adds it to the vector. Post that code and any problems you are having.

    Why are you using sleep()?
    Last edited by 7stud; 04-22-2006 at 01:20 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Replies: 4
    Last Post: 10-16-2003, 11:26 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Adding objects to an array
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 11-27-2001, 09:24 AM