Thread: Clarification on operator overloading

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    12

    Clarification on operator overloading

    I am just starting out a course in C++ programming at university, and I've been given this line of code in a header file named Card.h:

    Code:
    bool operator < (const Card& rhs) const;
    I'm meant to be writing an accompanying Card.cpp, but I don't quite understand what's going on in this line, so I was hoping that someone might be able to help. I know that rhs is a reference to a Card object, but is it meant to be comparing to something?

    Thanks in advance for your help!

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    That is an example of overloading the "<" operator. What you are comparing is the current object against the passed reference. Your implementation would look something like:

    Code:
    bool Card::operator < (const Card& rhs) const
    {
       if(this->data < rhs.data)
          return true;
       else
          return false;
    }
    The point is to compare two instances of the Card class. Then is can be used as follows:
    Code:
    Card c1;
    Card c2;
    if(c1 < c2)
       // do something...

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    12
    Thanks so much, that explained everything.

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Although one might implement it more like:

    Code:
    bool Card::operator < (const Card& rhs) const
    {
       return this->data < rhs.data;
    
       //if(this->data < rhs.data)
       //   return true;
       //else
       //   return false;
    }
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. srand() Clarification
    By Epo in forum C++ Programming
    Replies: 2
    Last Post: 03-03-2005, 11:05 PM
  2. Need a clarification here
    By bithub in forum A Brief History of Cprogramming.com
    Replies: 30
    Last Post: 12-27-2004, 01:06 AM
  3. exercise clarification truth table
    By curlious in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2003, 07:28 PM
  4. A little clarification?
    By Dr Nick in forum C++ Programming
    Replies: 2
    Last Post: 06-20-2002, 01:47 PM
  5. Clarification of Function Templates
    By biosx in forum C++ Programming
    Replies: 2
    Last Post: 02-20-2002, 11:42 AM