i am trying to write a very simple code as a practice. The problem is when i make friend a member function of one class to another, it says inaccesible but when i declare the whole class as friend of another class it works fine.
#include <iostream>
using namespace std;
class gpa2;
class gpa1 {
private:
int no1;
int no2;
public:
void setnum1(int n1, gpa2&xp) {
cout << " the friend member function is : " << xp.no4;
}
void setnum2(int n2) {
no2 = n2;
cout << "num2 is : " << no2 << endl;
};
};
class gpa2 {
private:
int no3;
int no4;
friend void gpa1::setnum1(int, gpa2&);
public:
void setnum3(int n3) {
no3 = n3;
cout << "num3 is : " << no3 << endl;
}
void getnum4(int n4) {
cout << "num4 is : " << n4 << endl;
}
};
int main() {
gpa1 g1;
gpa2 g2;
g1.setnum1(15, g2);
g1.setnum2(30);
g2.setnum3(45);
g2.getnum4(50);
return 0;
}
xp.no4
is not accessible, as setnum1
is a member function of gpa1
, not gpa2
Implementing the function setnum1(int, gpa2&)
is not necessary when defining it, and causing problems here: At the time of defining class gpa1
setnum1
can't be implemented, as class gpa2
is not yet defined. BUT implementing it after defining gpa2
is no problem at all.
Therefore, with some small changes: Godbolt example
#include <iostream>
using namespace std;
// forward declaration
class gpa2;
class gpa1 {
private:
int no1;
int no2;
public:
void setnum1(int n1, gpa2& xp);
void setnum2(int n2) {
no2 = n2;
cout << "num2 is : " << no2 << endl;
};
};
class gpa2 {
private:
int no3;
int no4;
friend void setnum1(int, gpa2&);
public:
void setnum3(int n3) {
no3 = n3;
cout << "num3 is : " << no3 << endl;
}
void getnum4(int n4) {
cout << "num4 is : " << n4 << endl;
}
int num4() { return no4; } // added accesibility to no4
};
// implementation of setnum1
void gpa1::setnum1(int n1, gpa2& xp) {
cout << " the friend member function is : " << xp.num4();
}
int main() {
gpa1 g1;
gpa2 g2;
g1.setnum1(15, g2);
g1.setnum2(30);
g2.setnum3(45);
g2.getnum4(50);
return 0;
}