Apprentice Programmer
Apprentice Programmer

Reputation: 1515

overloading operator function==

I'm not familiar with C++, and my instructor provided a function that i'm confused about

     operator long (void);
      long operator == (Base & base) {
       return ! strcmp (name, base);
          }

As far as i know, the operator is doing a comparison on 2 Base objects? Or am i wrong? When i call the function itself, its telling me that there is no such function call.

I call the function it returns this error

no matching function for... operator(Base*&,Base&)

Upvotes: 0

Views: 149

Answers (3)

KBi
KBi

Reputation: 383

You can define this operator in two ways. First is inside your Base class.

class Base
{
    public:
    long operator==(Base &base);
}

long Base::operator==(Base &base)
{
    ...
}

and the second is outside any class,

long operator==(Base &left, Base &right)
{
    ...
}

Note that the one declared outside any class must take two parameters, and the one inside the class must take just one. When you call it like this,

base1 == base2;

If you use the first version, base1 is the object in which the operator is called, and base2 is passed as the parameter.

If you use the second version, base1 is passed as left, base2 as right.

From your error message, I suppose you tried to use the second type as I wrote in this example as if it was of the first type.

Upvotes: 0

Yogesh D
Yogesh D

Reputation: 1681

There are two ways overloading an operator.

1.It can be a member of a class or

2.It can be outside class

Way of calling the overloaded operator function depends and vary on which way you use. In your case it seems to be inside class but i suppose there is something wrong in declaration and its not properly declared. Check this question link might be useful Operator overloading outside class

long operator == (Base &base); // this should be your declaration inside your class

//definition
long operator == (Base &base){
  return !strcmp(name,base.name); 
}

and you can call it over your class' object simply by

obj1==obj2 or obj1.operator==(obj2)

think this is useful

Upvotes: 1

Paweł Stawarz
Paweł Stawarz

Reputation: 4012

The function isn't named operator, it's named operator==. It's an overloaded comparison operator. You just call it like this:

Base a, b;
if(a==b) // <-- this is the function call
   std::cout<<"equal"<<std::endl;
else
   std::cout<<"not equal"<<std::endl;

Of course this is the case when the function is a member of the Base class. You didn't provide all of the code, so I'm guessing it is.

On top of that, the 1st line of your code is a declaration of another overloaded operator (one that converts the class to long), and it's implementation is provided somewhere else (probably).

Upvotes: 3

Related Questions