3

Inside one of my classes i've got a

Reservation * availability[30] = {nullptr};

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

Nevertheless, I've got a getReservations() function which is supposed to return a reference to that array of 30 elements, so that it can be used like:

getReservations()[i] ...

How should I declare that function?

4
  • Side note: I'd personally initialize the array with = {};. It looks like you think all of the elements are initialized to the nullptr you've written, but they're actually value-initialized. Commented May 7, 2017 at 20:13
  • 2
    @Quentin well, value-initialization and nullptr initialization do the same thing, don't they? I agree though, it's silly to treat the first element differently. Commented May 7, 2017 at 20:15
  • 1
    @user2079303 yes, that's my point. There's no functional difference but it is a bit misleading. Commented May 7, 2017 at 20:16
  • @Quentin my point is that is it really misleading when it leads to the same result with no difference? It's just silly in my opinion. Commented May 7, 2017 at 20:18

3 Answers 3

5

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

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

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

using Reservations = Reservation * [30];

Reservations & getReservations();

Or, because arrays aren't bounds-checked anyway, just return a pointer which you can then index like an array:

Reservation * getReservations();
Sign up to request clarification or add additional context in comments.

Comments

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

should do it for you.

Please remember of dangling references and pointer management.

Comments

1

I would recommend you to use modern C++:

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

ReservationArray _availability;

and to return that as:

ReservationArray& getReservations()

3 Comments

raw pointers are still incredibly useful in modern C++. Don't mistake "pointers" for "owning dynamic values". Those are orthogonal concepts.
true, they are useful in some specific cases. But why would you recommend using raw pointers here?
You made the (unsubstantiated) assumption that these pointers own data. If they're non-owning, then unique_ptr causes double delete undefined behavior, which is very very bad. These pointers could just as likely be nullable references, in which case Reservation* is the correct thing to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.