1

I created one new class which is publicly inherited from the string class. I wish to overload the < (less than) operator in the derived class. But from the overloaded function I need to call the parent class < operator. What is the syntax for calling this function? I would like to implement the operator as a member function if possible.

In Java there is super keyword for this.

My code is given below.

#include<iostream>
#include<string>
using namespace std;    
class mystring:public string
    {
     bool operator<(const mystring ms)
     {
      //some stmt;
      //some stmt;
      //call the overloaded <( less than )operator in the string class and return the value
      }

    };
user229044
  • 232,980
  • 40
  • 330
  • 338
Able Johnson
  • 551
  • 7
  • 29

2 Answers2

1

Calling a base class operawtor is easy if you realize that it is just a function with a funny name:

bool operator<(const mystring ms)
{
  //some stmt;
  //some stmt;
  return string::operator<(ms);
}

Alas, that does not work with std::string because operator< is not a member function, but a free function. Something like:

namespace std
{
    bool operator<(const string &a, const string &b);
}

The rationale is the same, call the funny named function:

bool operator<(const mystring ms)
{
  //some stmt;
  //some stmt;
  operator<(*this, ms);
}
rodrigo
  • 94,151
  • 12
  • 143
  • 190
1

std::string doesn't have a member overload of operator<, there is a free function template for operator< that operates on std::string. You should consider making your operator< a free function to. To call the operator< that operates on std::string, you can use references.

E.g.:

const std::string& left = *this;
const std::string& right = ms;
return left < right;
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • Thank you very much! This one works perfectly. Could you please answer one more doubt.If it is a free function template ,by default It should work for mystring also.But compiler gives error when I delete the operator < function from mystr. – Able Johnson Feb 12 '14 at 14:47
  • @AbleJohnson: What error does the compiler give and what does the code that gives this error actually look like? – CB Bailey Feb 12 '14 at 15:07
  • `#include #include using namespace std; class mystring:public string { }; int main() { mystring a,b; cout< – Able Johnson Feb 12 '14 at 15:16
  • @AbleJohnson: You probably meant `cout<<(a – CB Bailey Feb 12 '14 at 16:52