roulette01
roulette01

Reputation: 2472

operator<< overloading "error: passing 'const...."

ofstream& operator<<(ostream &outStream, const EventClass &eventObject)
{
  outStream << eventObject.getEventName() << " event at "
    << eventObject.getEventTime() << endl;

  return(outStream);
}

I believe this snippet is sufficient to analyze the error.

When I compile my code I get the following errors:

error: passing ‘const EventClass’ as ‘this’ argument of ‘std::string EventClass::getEventName()’ discards qualifiers [-fpermissive]
outStream << eventObject.getEventName() << " event at "

error: passing ‘const EventClass’ as ‘this’ argument of ‘int EventClass::getEventTime()’ discards qualifiers [-fpermissive]
<< eventObject.getEventTime() << endl;

error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::ostream {aka std::basic_ostream}’
return(outStream);

Any ideas how to solve these errors?

Upvotes: 0

Views: 966

Answers (2)

sjrowlinson
sjrowlinson

Reputation: 3355

You need to make sure getEventName and getEventTime are declared as const, as follows:

std::string getEventName() const;
int getEventTime() const;

in the declaration and implementation of EventClass. This tells the compiler that these methods will not modify the fields of the object in any way.

Also, the last line of the operator should simply be: return outStream;

Edit: also std::ofstream is not the same as std::ostream. Generally, for operator<<, it needs to be defined as:

std::ostream& operator<<(std::ostream& os, const EventClass& eventObject) { 
    //blah 
}

to encompass any stream type.

Upvotes: 3

Remy Lebeau
Remy Lebeau

Reputation: 598134

eventObject is a reference to a const object, so its getEventName() and getEventTime() methods need to be declared as const as well, to specify that they don't modify the object they are called on, eg:

std::string getEventName() const;
int getEventName() const;

Also, your operator is declared as returning an ofstream, but it needs to return an ostream instead, to match the input:

ostream& operator<<(ostream &outStream, const EventClass &eventObject)

Upvotes: 1

Related Questions