Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why overloaded ' operator < ' should be const for class?

Can anybody explain this behavior in context of STL sort algorithm? If operator < is not defined const it gives error,

error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive] while (__pivot < *__last)

Is sort algo lhs const object or sort is const method?

class B
{
 public:
    ...
    bool operator < (const B& b) const       // why const required here?
    {
        return (m_i < b.m_i);
    } 
    ...

 private:
    int m_i;
    int m_j;
};

int main()
{
  vector<B> Bvec2 {B(5), B(3), B(30), B(20), B(8)};
  std::sort(Bvec2.begin(), Bvec2.end());
  ...
}
like image 424
deepdive Avatar asked May 29 '14 06:05

deepdive


People also ask

Why do we use const in operator overloading?

The const qualifier ensures that the parameter (param) is not altered inside the operator=() method. The above method alters the right hand side operand 'param' after assigning the value to the left hand side operand. The const qualifier helps you not to violate the semantics of the assignment operation.

Which statement is best fit for operator overloading?

Which is the correct statement about operator overloading? Explanation: Both arithmetic and non-arithmetic operators can be overloaded. The precedence and associativity of operators remains the same after and before operator overloading.

What is constant overloading?

const overloading is when you have an inspector method and a mutator method with the same name and the same number of and types of parameters. The two distinct methods differ only in that the inspector is const and the mutator is non- const . The most common use of const overloading is with the subscript operator.

What are the limitations of operator overloading?

1) Only built-in operators can be overloaded. New operators can not be created. 2) Arity of the operators cannot be changed. 3) Precedence and associativity of the operators cannot be changed.


1 Answers

Marking the function as const promises that it will not change the object. So it can be used on const objects.

The STL almost certainly takes the arguments as const, because that is the smart thing to do.

It shouldn't hurt you to define operator< as const because I cannot imagine having a less-than operator that changes the object. That would just be silly.

If you want to know exactly where here is some code copied out of libstdc++ bits/stl_algo.h on a Fedora 20 machine:

  /// This is a helper function...
  template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
    _RandomAccessIterator
    __unguarded_partition(_RandomAccessIterator __first,
                          _RandomAccessIterator __last,
                          const _Tp& __pivot, _Compare __comp)

const _Tp& __pivot, right there.

like image 96
Zan Lynx Avatar answered Sep 28 '22 19:09

Zan Lynx