0

I have the function prototype in .h file as:

myClass & operator+ (const myClass & myClassInst) const;

and the implementation in .cpp file:

myClass& myClass::operator+ (const myClass &myClassInst) const
{
    return *this;
}  

However, when I compile, I get the following message:

error C2440: 'return' : cannot convert from 'const class myClass' to 'class 
myClass &' 

I am a little bit confused by *this here, and I simply couldn't make things correct. Does anybody know how to fix the error here?

Thanks in advance!

Cindy
  • 163
  • 2
  • 9
  • https://stackoverflow.com/a/4421719/920069 – Retired Ninja Jun 23 '18 at 22:44
  • Possible duplicate of [Meaning of 'const' last in a function declaration of a class?](https://stackoverflow.com/questions/751681/meaning-of-const-last-in-a-function-declaration-of-a-class) – Nyque Jun 23 '18 at 22:50
  • 8
    BTW. This operator should not return a reference. – user3366592 Jun 23 '18 at 22:56
  • 2
    And it should be a free function, not a member. –  Jun 23 '18 at 22:58
  • 2
    Handy reading: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Jun 23 '18 at 23:07
  • @NeilButterworth there is nothing wrong with defining `operator+` as a member of the class, as long as it follows the rules for input and output. Making it a free function is just a rule of thumb, not set in stone. – Remy Lebeau Jun 23 '18 at 23:27
  • @Remy If you say so - I have never seen operator +, or any other binary operators (except for assignment) defined as anything but free functions, or done so myself. But YMMV. –  Jun 23 '18 at 23:35
  • Possible duplicate of [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Joseph D. Jun 23 '18 at 23:39

1 Answers1

1

The problem is you're returning a reference to an object from a member function that you explicitly declared as const.

A const member function guarantees that your object and its attributes won't be modified (unless they're declared as mutable).

By returning a reference to this (*this) the caller of the function can freely change the object and that would break the const member function warranty.

So either make your member function non-const, or don't return a reference.

gedamial
  • 1,498
  • 1
  • 15
  • 30
  • Or return a const reference? (Not sure how advisable that is, but it makes the syntax work.) – JaMiT Jun 24 '18 at 04:06