0

I am learning about friends in classes and my problem is: I want funcC3() to set and permanently change C1::a value, how to do it? I want global function gfunc() to be able to do the same, how? Could you please provide me the way i do it, because in the book they don't specify?

#include <iostream>
using namespace std;

class C2;

class C3
{
public:
    void funcC3(int const& x)
    {
        cout << "in third class...: " << x << endl;
    };
};

class C1
{
private:
    int a;
public:
    void funcC1()
    {
        cout << "inside C1 private thingie: " << a << endl;
    };
    int C1::getcha();
    friend class C2;
    friend int gfunc(int chair);
    friend void C3::funcC3(int const& a);
};

int C1::getcha()
{
    return a;
};

class C2
{
public:
    int a;
};

**int gfunc(int ch)**
{
    int chair = ch;
    return chair;
};

**int main()**
{
    C1 obj1;
    C3 obj3;

    obj3.funcC3(10);
    obj1.funcC1();

gfunc(12);
cout << C1.geta() << endl;
    system("pause");
}
steveax
  • 17,527
  • 6
  • 44
  • 59
beginh
  • 1,133
  • 3
  • 26
  • 36

1 Answers1

0

I want funcC3() to set and permanently change C1::a value, how to do it?

Declare it as friend function in C1:

class C1; //forward declaration

class C3
{
//...
    void funcC3( C1& c);
};

class C1
{
//...
private:
    int a;
    friend void C3::funcC3( C1&);
};

void C3::funcC3( C1& c) { c.a = 100;}

I want global function gfunc() to be able to do the same, how?

Same as above:

class C1;
void gfunc( C1& c);

class C1 {
//...
private:
    int a;
    friend void gfunc( C1& c);
};

void gfunc( C1& c) { c.a = 100;}
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • thanks, i had bad approach :). about gfunc(), if I want to pass parameter 100 from main in form of gfunc(C1& c, int par), i get **errorC2248 that it cannot access private parameter from class.** I thought it's better to be able to parametrize in such a way? – beginh Mar 03 '14 at 18:25
  • 1
    you can access private members of C1 instance if it was passed to its friend function – 4pie0 Mar 03 '14 at 18:28
  • you mean passed explicitly private **a** in this case? because i thought if we pass the whole **C1& c**, among it also a member a.. – beginh Mar 03 '14 at 19:03
  • you can pass value of c.a to use it in function, or reference to c.a if you can access it or you can pass object c to friend function and access c.a in function – 4pie0 Mar 03 '14 at 19:05