When i execute the code below it generates 2 errors c1::x is not accessible and missing ) in line9. Please explain. Thanks in advance...
#include<iostream>
class c1{
int x;
public:
void input(){
cout<<"Enter length : ";
cin>>x;
}
friend void output(c1 obj1, c2 obj2);
};
class c2{
int y;
public:
void input(){
cout<<"Enter breadth : ";
cin>>y;
}
friend void output(c1 obj1, c2 obj2);
};
void output(c1 obj1, c2 obj2){
cout<<"Area is "<<obj1.x*obj2.y;
}
int main(){
c1 obj1;
c2 obj2;
clrscr();
obj1.input();
obj2.input();
output(obj1, obj2);
getch();
return 0;
}
The friend function needs to know that classes c1
and c2
exist. c1
is fine, because the friend is declared with in that class. But for c2
you need a forward declaration before the first friend
declaration:
#include<iostream>
using std::cin;
using std::cout;
class c2; // forward declaration
class c1{
....
friend void output(c1 obj1, c2 obj2); // OK now
};
I also added some missing declarations. You also need the headers for getch
and clrscr
.