Return an array of pointers by reference

Inside one of my classes, I have

Reservation * availability[30] = {nullptr};

      

(which I, of course, will later initialize with some values).

However, I have a getReservations () function that should return a reference to this 30-element array, so it can be used like:

getReservations()[i] ...

      

How do I declare this function?

+3


source to share


3 answers


The syntax for declaring a function that returns an array by reference is:

Reservation * (& getReservations())[30];

      

Of course, as you can see, you shouldn't be using this in real life. Instead, do it with a type alias:



using Reservations = Reservation * [30];

Reservations & getReservations();

      

Or, since arrays are unbounded anyway, just return a pointer, which can then be indexed as an array:

Reservation * getReservations();

      

+5


source


Reservation *(&getReservations())[30];

      

should do it for you.



Please be aware of dangling links and pointer management.

+4


source


I would recommend that you use modern C ++:

using ReservationArray = std::array<Reservation*, 30>;

ReservationArray _availability;

      

and return this as:

ReservationArray& getReservations()

      

+1


source







All Articles