0

When I try to call a friend function of a certain class by passing a reference to an object of said class via de-referencing the "this" pointer, Eclipse throws a type-mismatch error but the program still compiles and runs just fine.

To see if this was something exclusive to Eclipse I tried running the code with a few online compilers as well. onlinegdb and codechef compiled and ran without showing any errors. Since the program technically works I could just ignore this error and move on but since I don't want to run into any undefined behavior in the future, it might be best to get this sorted out right now.

#include <iostream>

class Foo
{
public:
    Foo ()
    {
        Bar (*this); //<---The error occurs on this line
    }
friend void Bar (Foo &);
};

void Bar (Foo &foo)
{
    std::cout << "Inside Bar()!" << std::endl;
}

int main ()
{
    Foo foo;
}

Error message:
Invalid arguments ' Candidates are: void Bar(Foo &) '

anon12c
  • 11
  • 3
  • Eclipse is not a C++ compiler. Only a C++ compiler can fully understand C++ code, and a real C++ compiler, like gcc, does not report any errors with the shown code. – Sam Varshavchik Jul 04 '19 at 20:58
  • Syntax checkers often struggle with correct C++ code, so I wouldn't worry about it. As a test you could try moving the friend declaration to the start of the `Foo` class, that might keep Eclipse happy. – john Jul 04 '19 at 20:59
  • @Sam Varshavchik Hey, that worked! Thanks a lot. I still would like to know the reason for this though. As far as I am aware, declarations of friend functions can be put anywhere in the class declaration. Besides, the error called for a type-mismatch not an unresolved symbol. What are your thoughts on this? Anyway, thanks again! – anon12c Jul 04 '19 at 21:01
  • @john That's exactly the explanation that I was looking for! Thank you. I would upvote your comment but unfortunately I don't have enough karma for that. – anon12c Jul 04 '19 at 21:04

1 Answers1

0

Moving the friend declaration to the top of the class declaration fixed the issue. Apparently, this was happening due to Eclipse's syntax checker not being able to properly check the code.
Thanks to @Sam Varshavchik and @john for their helpful replies.

anon12c
  • 11
  • 3