Matt
Matt

Reputation: 879

C++ header/implementation file and overloaded operators

It's not often that I work in C++ and I've run into a simple error that is holding me up.

In Xcode I have the following two errors: In Event.h: Control reaches end of non-void function In Event.cpp: Overloaded operator must have at least one argument of class or enumeration

Both errors are at the lines of the method signature for

bool operator () (Event *left, Event *right)

Here are the .h and .cpp files in their entirety (not that much going on yet): Event.h

#ifndef __EventSimulation__EventComparison__
#define __EventSimulation__EventComparison__

#include <iostream>
#include "Event.h"
class EventComparison {
public:
    bool operator () (Event *left, Event *right){}

};
#endif

Event.cpp

#include "EventComparison.h"
#include "Event.h"

bool operator() (Event *left, Event *right) {
    return left->time > right->time;
}

Can someone please help me fix this error and explain what/why things are issuing a compile error and how to avoid this in the feature. Thanks for your help!

Upvotes: 1

Views: 9423

Answers (2)

rici
rici

Reputation: 241911

bool operator () (Event *left, Event *right){}

defines a member function which does nothing. Such a function would have to have return type void, since it doesn't return anything.

On the other hand, your definition of the operator doesn't indicate that it is a class member.

In short, you need:

// Declaration
class EventComparison {
  public:
    // NOTE: const
    bool operator () const (Event *left, Event *right);
};

// Implementation
bool EventComparison::operator() const (Event *left, Event *right) {
      return left->time > right->time;
}

Upvotes: 2

mfuchs
mfuchs

Reputation: 2250

Change your header Event.h to

class EventComparison {
public:
    // the {} is the body of the function, therefore
    // you added a function defintion, though you did
    // not return a result
    // bool operator () (Event *left, Event *right){}

    // this is a function declaration:
    // the body of the function is not defined
    bool operator () (Event *left, Event *right);
};

What you did in the header is actualy define the function by adding the parenthesis.

Then in the source file do

bool EventComparison::operator() (Event *left, Event *right) {
     return left->time > right->time;
}

You defined a bool operator in global namespace, but what you wanted to do is define a member function. For this to happen you have to specify which class the function belongs to, which you can do via the EventComparison:: part.

Upvotes: 6

Related Questions