0

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?

kovac
  • 4,945
  • 9
  • 47
  • 90
  • 1
    Possible duplicate of [What do ‘value semantics’ and ‘pointer semantics’ mean?](https://stackoverflow.com/questions/166033/what-do-value-semantics-and-pointer-semantics-mean) – L. F. Mar 17 '19 at 13:33
  • @L.F. It didn't help me. In fact it was just more confusing. – kovac Mar 17 '19 at 13:40
  • 1
    Pay special attention to [this answer](https://stackoverflow.com/a/166048). – L. F. Mar 17 '19 at 13:41

2 Answers2

2

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.

Yashas
  • 1,154
  • 1
  • 12
  • 34
2

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.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • The reason why this happens is because of the implementation of the assignment operator in vector? – kovac Mar 17 '19 at 13:44
  • @swdon No. That is what normally happens when you use `=`. See also https://stackoverflow.com/questions/166033/what-do-value-semantics-and-pointer-semantics-mean/166048#166048 – Jesper Juhl Mar 17 '19 at 13:49