Search code examples
c++compiler-errorsfriend

unqualified id before a friend function


I am getting the error below:

..\src\test.cpp:17:20: error: expected unqualified-id before 'try'
         friend int try(Complex);

Please help and tell me why this code is producing errors:

#include <iostream>
using namespace std;
class Complex
{
private:
    int a, b;
public:
    showData()
    {   
        cout<<"\na= "<<a<<" b= "<<b;
    }
    Complex(int x, int y)
    { //constructer
        a = x;
        b = y;
    }
    friend int try(Complex);
    //friend function
};
int try(Complex c)
{   
    cout<<"You areworking in try now";
    cout<<"\noutput from friend fun : "<<c.a<<" "<<c.b;
}
int main()
{
    Complex c1(3, 4);
    try(c1);
    return 0;
}

Solution

  • First let's simplify the problem to a Minimal Complete and Verifiable example that duplicates the problem:

    int try;
    

    Not much code is required because try is a reserved word. You cannot use try in a program without the compiler expecting a try/catch` block.

    Solution: Do not use try as an identifier. Instead use try_func or something that describes what is being tried.

    Additional note: showData() needs a return type. Most likely it should be void showData()