0

i am trying to write a program for friend functions but it isnt working. :(

#include <iostream>

using namespace std;

class Z;
{
    private:
    int a;
    friend void fn();
};
void fn()
{
    Z one;
    one.a=5;
    cout<<a<<endl;
}
int main()
{
    fn();
    return 0;
}

can someone please tell whats wrong with that code.

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by Srinivas0
0

Hi,

There are 2 mistakes in your code.

line no: 4 class Z; // here you have to remove the semicolon
line no: 15 cout<<a<<endl; // here a is a member variable that you can't access directly. so use the object and access it . here the object is one.
so try it like : cout << one.a << endl;

Find the working code before.


#include <iostream>

using namespace std;

class Z
{
private:
int a;
friend void fn();
};

void fn()
{
Z one;
one.a=5;
cout << one.a << endl;
}

int main()
{
fn();
return 0;
}

BR/ KMat
-----------------------------------------------------------------------------

i am trying to write a program for friend functions but it isnt working. :(

#include <iostream>

using namespace std;

class Z;
{
    private:
    int a;
    friend void fn();
};
void fn()
{
    Z one;
    one.a=5;
    cout<<a<<endl;
}
int main()
{
    fn();
    return 0;
}

can someone please tell whats wrong with that code.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.