1

I am practicing basic OOP w/ C++ and while using a pointer I found that I did not need to dereference the pointer to assign a value. Why is this? Menu.h:

class Menu { public:
int MenuCount;
int NumItems;
Drinks *Items;

Menu.cpp

Menu::Menu(Drinks a, Drinks b, Drinks c)  {
std::cout << "How many items would you like on this menu? "; std::cin >> NumItems;
Items = new Drinks[NumItems];
Items[0] = a; Items[1] = b; Items[2] = c; // why is it I can assign values by pointer without dereferencing? 
MenuCount = 3;

To my understanding I would've had to dereference Items with * prior to assigning a new object to the array, nonetheless this code works.

0

3 Answers 3

1

The [] operator implicitly dereferences the pointer. It hides the pointer arithmetic with arrays, and because arrays decay to pointers to the first element, it works just as well on a pointer as an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the clarification
1

In your case, Items[0] is actually the same as *(Items + 0) so it is already doing the dereference for you.

1 Comment

Thank you this was quite helpful as well
0
Menu::Menu(Drinks a, Drinks b, Drinks c)  {
    std::cout << "How many items would you like on this menu? "; std::cin >> NumItems;
    1#  Items = new Drinks[NumItems];
    2#  Items[0] = a; Items[1] = b; Items[2] = c; // why is it I can assign values by pointer without dereferencing? 
    MenuCount = 3;
}
  1. We are assigning a pointer to a pointer, new Drinks[] will create an array on the heap and return a pointer to it.

  2. Items[0] is the same as (*Items + 0), it'll increment the pointer dereference it at that point.

Comments

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.