Thread: Array of pointers

  1. #1
    Student
    Join Date
    Oct 2005
    Posts
    6

    Array of pointers

    Hi,

    How do I declare an array of pointers, which are pointing to a class I've created myself?

    So then I can do something like this:

    pnt_array[4] = new MyClass(5);

    Thank you for any help.

    Jonny Wong

  2. #2
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Code:
    ClassName **pnt_array = new ClassName*[4];


    and here is one way you could populate your array of pointers to your class object:

    Code:
    for(int i=0; i<4; i++)
    
         pnt_array[i] = new ClassName;


    dereference your array like this:

    Code:
    pnt_array[i]->function() ;


    free the array like this:

    Code:
    for(int i=0; i<4; i++)
    
         delete pnt_array[i];
    
    delete [] pnt_array;
    Last edited by The Brain; 11-27-2005 at 07:53 PM.
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    How do I declare an array of pointers, which are pointing to a class I've created myself?
    Hi,

    Here is how you declare an array of int's:

    int nums[20];

    More generally, to declare any array you first list the type of the elements you want to store in the array, then the array name, then the size of the array between brackets. You said you want an array that will store pointers to your class, so that means the type of the elements you want to store in the array will be: YourClass*.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning an Array of Pointers to Objects
    By randomalias in forum C++ Programming
    Replies: 4
    Last Post: 04-29-2006, 02:45 PM
  2. two-dimensional dynamic array of pointers to classes
    By Timo002 in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 06:18 AM
  3. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 06:58 PM
  4. array of pointers to struct array
    By eth0 in forum C++ Programming
    Replies: 1
    Last Post: 01-08-2004, 06:43 PM
  5. array of pointers to structs
    By stumon in forum C Programming
    Replies: 7
    Last Post: 03-24-2003, 07:13 AM