c++pointers

How do I create an array of class pointers with new?


I'm a little bit confused.

I have this code:

class Fish {
public:
       void Swim()
       {
            std::cout << "I'm Swiming" << std::endl;
       }
};

Now, in another class, I want to do an aggregation of an array of this class:

class Pool {
     Fish ** fishes;
public:
     Pool(int p_fishes)
     {
         fishes = new Fish[p_fishes]
     }
     ~Pool()
     {
         delete[] fishes
     }
};

What I really want to do is to create an array of Fish* without being hard-coded like:

 Fish* fishes[8];

Is there any way to do this with new?


Solution

  • Fish* fishes[...]; is a fixed-length array holding Fish* pointers.

    new Fish[...] is a dynamic-length array holding Fish objects.

    In general, new T[N] returns a T* pointer to an array of N number of T objects.

    In your case, T is Fish, so new Fish[] returns a Fish* pointer. You can't assign a Fish* pointer to a Fish** pointer, like you are trying to do.

    If you really want an array of Fish* pointers, you need to use new Fish*[...] instead, which returns a Fish** pointer that you are looking for, eg:

    class Pool {
         Fish ** fishes;
         int num_fishes;
    public:
         Pool(int p_fishes)
         {
             num_fishes = p_fishes;
             fishes = new Fish*[p_fishes];
             for(int i = 0; i < p_fishes; ++i) {
                 fishes[i] = new Fish;
             }
         }
    
         ~Pool()
         {
             for(int i = 0; i < num_fishes; ++i) {
                 delete fishes[i];
             }
             delete[] fishes
         }
    };
    

    Note: this is just an example to answer your specific question. This is NOT the kind of code you should be writing in general. For instance, Pool as shown does not follow the Rule of 3/5/0, and is also not exception-safe. Consider using std::vector<Fish> instead.