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.

Recommended Answers

All 2 Replies

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.

thx for the help

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.