Search code examples
c++visual-studio-2010functionpointersdynamic-arrays

How to return a dynamic arrays of pointers from a method


Please have look at the following code

VehicleManager.h

#pragma once
#include "Vehicle.h"

class VehicleManager
{
public:
    VehicleManager(int size);
    ~VehicleManager(void);

    bool add(Vehicle *v);
    void display();
    int getCount();
    Vehicle **getList();

private:
    int count;
    int maxVehicles;
    Vehicle** vehicles;
};

VehicleManager.cpp

//Other Code

Vehicle VehicleManager::**getList()
{
    return vehicles;
}

//Other Code

In here, I am unable to return the array. How can I return a dynamic arrays of pointer from a function? Please help!


Solution

  • Apply the ** to the return type:

    Vehicle** VehicleManager::getList()
    {
        return vehicles;
    }
    

    But what you should really do is use an std::vector<Vehicle*> if the VehicleManager is in charge of the lifetime of the dynamicallly allocated Vehicles , or an std::vector<std::unique_ptr<Vehicle> if the caller is to take ownership. In both cases you can return it by value.