Innkeeper
Innkeeper

Reputation: 673

Having trouble maintaining const correctness with parameter passed by reference

I'm sure this has been asked before, but all the search results have const& questions.

I want to make sure the following method doesn't change the GuestNode passed to it, so I wanted to pass const GuestNode& guest, but g++ won't let that happen, because I'm assigning the &guest to pointers. Why does that happen? And how can I make sure the passed param stays as it was?

   void GuestList::Add(GuestNode& guest)
   {
      if ( first == 0 )
      {
         //first guest
         first = &guest;
      }
      else
      {
         //nth guest
         GuestNode *p = first;
         while ( p->next != 0 )
            p = p->next;
         p->next = &guest;
      }
      SetCount(GetCount() + 1);
   }

Upvotes: 0

Views: 82

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110748

If you make guest a const GuestNode&, then &guest is a const GuestNode*. That is, it's a pointer to a const GuestNode. That makes sense, otherwise you'd be able to modify the const object through the non-const pointer to it. So if you're going to assign that pointer to first and/or p, you need to make sure that they are const GuestNode*s too.

If you need first, which I'm assuming is a member of GuestList, to be non-const, then you shouldn't be taking a const reference.

To demonstrate:

const int x = 5;
int* p = &x; // error: invalid conversion from ‘const int*’ to ‘int*’

Imagine if this weren't an error, I'd then be able to do *p = 10; to change the value of x, even though the object is supposed to be const.

Upvotes: 1

Related Questions