This a basic program to understand how to use friend class
in C++.
Class xxx
has a class yyy
object using friend
. Since class yyy
is defined after class xxx
I have declared class yyy
using forward
declaration.
#include<iostream>
using std::cout;
using std::endl;
class yyy; //Forward Declaration of class yyy
class xxx{
private:
int a;
public:
xxx(){a=20;yyy y2;y2.show();} //Error//
void show(){cout<<"a="<<a<<endl;}
friend class yyy; //Making class yyy as freind of class xxx
};
class yyy{
private:
int b;
public:
yyy(){b=10;}
void show(){cout<<"b="<<b<<endl;}
};
int main(int argc, char *argv[])
{
xxx x1; //creating xxx object and calling constructor
x1.show();
return 0;
}
When I compile the program I get this error:
error: aggregate ‘yyy y2’ has incomplete type and cannot be defined
I referred to this link recursive friend classes and someone had answered like this https://stackoverflow.com/a/6158833/2168706
I am following this approach but I am still unable to solve the issue. Please provide a solution if any exists and please let me know if I am wrong at any point in the code.