Search code examples
c++constantspass-by-reference

Passing a vector by const rerefence and adding an element to the vector


I'm trying to understand the following member function:

void Date::setDays(const std::vector<Date> &days){
  Date d(1, 1, 1);
  m_days = days;
  m_days.push_back(d); // valid.
  days.push_back(d); // invalid.
}

In the member function above that belongs to the class Date, I'm passing days by reference as a const. I can understand why it is illegal to add an element to days as it is const. However, my confusion is, how is it possible that I can add an element to m_days? Doesn't it refer to the same vector as days? When I add an element to m_days, does it mean I'm adding an element to days too?


Solution

  • You assign m_days a copy of days. It is not the same vector and if m_days is not const (which it obviously is not since you just assigned to it) then adding elements to it is just fine. Nothing you do to m_days affects days in any way.