-4

I am getting the following error:

Conversion loses qualifiers

when trying to implement indexing operator without the code duplication (I will show the segment of code):

Point* BufferedList::indexTemp(size_t idx)
{
    if (idx >= size) return nullptr;

    return &arr[idx];
}

const Point* BufferedList::operator [](size_t idx) const
{
    return indexTemp(idx);
}
Point* BufferedList::operator [](size_t idx)
{
    return indexTemp(idx);
}

However, the following works (this doesn't use the helper function indexTemp and it is duplication of code):

const Point* BufferedList::operator [](size_t idx) const
{
    if (idx >= size) return nullptr;

    return &arr[idx];
}
Point* BufferedList::operator [](size_t idx)
{
    if (idx >= size) return nullptr;

    return &arr[idx];
}

Do I really need two functions for indexing (one that returns Point* and the other that returns const Point*)?

user156262
  • 37
  • 1
  • 8
  • 1
    in this case I would just use the duplicate code – bolov Nov 21 '17 at 09:51
  • 2
    There are a million duplicates of this already. Did you search at all? e.g. https://stackoverflow.com/questions/27825443/same-function-with-const-and-without-when-and-why / https://stackoverflow.com/questions/856542/elegant-solution-to-duplicate-const-and-non-const-getters / https://stackoverflow.com/questions/1537271/why-do-we-need-both-const-and-non-const-getters-in-this-example / https://stackoverflow.com/questions/13479548/why-having-const-and-non-const-accessors – underscore_d Nov 21 '17 at 09:51

1 Answers1

4

It is because you call a non const function from a const function. The compiler warns you that your const object will be no more const in temp function.

informaticienzero
  • 1,616
  • 1
  • 10
  • 20