A pointer to an array of object pointers, which point to objects

This is a discussion on A pointer to an array of object pointers, which point to objects within the C++ Programming forums, part of the General Programming Boards category; Hi, say i have got the following class called X. I want to be able to create a pointer to ...

  1. #1
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359

    A pointer to an array of object pointers, which point to objects

    Hi, say i have got the following class called X. I want to be able to create a pointer to an array of type X pointers, which then be instantiated into objects. I have tried the follwing, but with no success. Any help would be greatly appreciated.

    Code:
    int NumObjs = 2;
    
    X **Test;
    
    *Test = new X[NumObjs];
    
    for(int ObjNum; ObjNum < NumObjs; ObjNum++)
      Test[ObjNum] = new X(/*Whatever*/);
    I need to be able to access the objects using the following notation: Test[0]->Member; Thanks.
    Be a leader and not a follower.

  2. #2
    Registered User Cela's Avatar
    Join Date
    Jan 2003
    Posts
    362
    First you allocate NumObj X *'s, then loop through those pointers and allocate real X's :-)
    Code:
    #include <iostream>
    
    using namespace std;
    
    class X {
    public:
      int stuff;
    };
    
    namespace {
      const int NumObj = 2;
    }
    
    int main()
    {
      X **test;
    
      test = new X *[NumObj];
    
      for (int i = 0; i < NumObj; i++)
      {
        test[i] = new X;
      }
    
      // Use and delete
    }
    /*
    test->[0]->X Obj
          [1]->X Obj
    */
    *Cela*

  3. #3
    Registered User subdene's Avatar
    Join Date
    Jan 2002
    Posts
    359
    Cela, you are fantastic, wonderful, amazing, and everything else. You don't know what a headache i've had with that. Again, thank you so much yet again! YES!!!!!!!!!!!!!!!! IT WORKS!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Be a leader and not a follower.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 05:23 AM
  2. sorting with pointer of pointers to array
    By dunpealslyr in forum C++ Programming
    Replies: 6
    Last Post: 10-02-2007, 12:26 AM
  3. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 05:33 PM
  4. Replies: 41
    Last Post: 07-04-2004, 04:23 PM
  5. Creating an array of object pointers
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 10-08-2001, 11:01 PM

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