CPP Arrays and the Free Store

Using objects in arrays

  • Any object, whether built-in or user defined, can be stored in an array.
  • Accessing member data in an array of objects is a two-step process.
    1. Identify the member of the array by using the index operator ([ ]).
    2. Add the member operator (.) to access the particular member variable.
    Cow Farm[6];
    int i;
    for (i = 0; i < 6; i++){
    // The Farm[i] returns the object of a Cow
       Farm[i].setAge(2*i +1);
    }

Declaring Arrays on the Free Store.

  • As for any object, you can declare an array of object on the free store with the new keyword.
    Cow *pFarm = new Cow[500];  // pFarm is a pointer to an array of 500 Cow objects
    Cow *pCow = pFarm;          // pCow points to pFarm[0]
    pCow->setAge(10);           // set pFarm[0] to 10
    pCow++;                     // advance to pFarm[1]
    pCow->setAge(20);           // set pFarm[1] to 20
  • Be aware of that:
    Cow   pOne[50];             // Is an array of 50 Cow objects
    Cow * pTwo[50];             // Is an array of 50 pointers to Cow objects
    Cow * pThree = new Cow[50]; // Is a pointer to an array of 50 Cow objects
    
    Please remember that pOne and pThree have instances of Cow, but pTwo is only an array with no Cow object instance.
  • You find an program example in the Aggregation and Delegation session.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.