Array of class objects

This is a discussion on Array of class objects within the C++ Programming forums, part of the General Programming Boards category; How'd i make an array of class type objects here is my current call to create an instance..... Code: cannon ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    34

    Array of class objects

    How'd i make an array of class type objects here is my current call to create an instance.....

    Code:
    cannon * cball = new cannon(45,90,5);
    This create an instance of cannon but i want multiple simultaneous instances by creating an array of them how'd i do that please?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Depends on what you want to do. Something like this for example:
    Code:
    const int max_balls = 5;
    cannon *cballs[max_balls];
    for(int i = 0; i < max_balls; i++)
       cballs[i] = new cannon(45+i, 90+2*i, 5);
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Chinese pâté foxman's Avatar
    Join Date
    Jul 2007
    Location
    Canada
    Posts
    404
    If you want an array of cannon objects:
    Code:
    cannon arr[] = {cannon(45, 90, 5), cannon(23, 23, 23), cannon(...)};   // array of 3 cannon object
    If you want an array of pointers to cannon object, then:
    Code:
    cannon *arr[] = {new cannon(45, 90, 5), new cannon(23, 23, 23), new cannon(...)};
    I hate real numbers.

  4. #4
    Registered User
    Join Date
    Jul 2008
    Posts
    34
    Thanks guys.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,318
    I would consider a vector<cannon>. You can't initialize each object inline to different values, but if they all have the same value you can initialize it on construction. If they don't you can just push_back each value one at a time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File handling with Array filled with a class
    By MarlonDean in forum C++ Programming
    Replies: 18
    Last Post: 06-27-2008, 10:53 AM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 12:01 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21