Friend functions?

A small code about friend functions. Why does it still say that a is private?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>

using namespace std;

class Stud
    {
        int a;

    public:
        friend int me(Stud b);
    };

int me(Stud b)
{
    return b.a;
}

int main()
{
    Stud c;
    c.a=10;
    me(c);
}


EDIT: Still won't work!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

class Stud
{
int a;

public:
friend int showme(Stud b);
friend void setme(Stud d);
};

int showme(Stud b)
{
return b.a;
}

void setme(Stud d, int e)
{
d.a=e;
}

int main()
{
Stud c;
setme(Stud c, 10);
showme(c);
}

Last edited on
c.a=10;

a is private to Stud
Hi,

You have granted friendship to the me function, which is fine. But it doesn't mean everything is a friend, so line 21 is an error.

Btw, the me function returns an int, but you don't do anything with it.

Your class needs a constructor with a member initialization list, so that the private variables are set with some values. That is the purpose of a constructor.

Good Luck !!
1
2
friend void setme(Stud d);
void setme(Stud d, int e)


They are two different functions, did you forget to add it to the friend parameters?

EDIT: By add it, I mean the int e parameter.


EDIT 2:

BTW this line here: setme(Stud c, 10);

You aren't using the previous Stud c you declared, you are creating an entirely new stud in the scope of the setme function. If you want to use the preveious Stud, reference it by name:

setme(c,10)
Last edited on
@jonsnoww

I don't think you should be using friend functions for these purposes.

Have a constructor set the member values initially. Have an ordinary public function: to return the value of a private member (aka a accessor function, get function); or to print a value; or overload the ostream << operator to print the values in the class. Have a public function to set the value of a member after the object is created - these are known as mutator or set functions.

Note that you don't necessarily have to have a get /set function for every member variable. Often one can combine them - one function to alter several variables.
Topic archived. No new replies allowed.