kovac
kovac

Reputation: 5389

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?

Upvotes: 0

Views: 45

Answers (2)

Jesper Juhl
Jesper Juhl

Reputation: 31459

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.

Upvotes: 2

Yashas
Yashas

Reputation: 1234

m_days = days makes a copy of the days array, i.e. m_days is another vector independent of days which has a copy of the days array. Any changes that you make to m_days will not affect days. Hence, the constness of days is not violated.

Upvotes: 2

Related Questions