I have one question about the following code snippet in c :
#include <iostream>
using namespace std;
class ABC;
class XYZ
{
int data;
public:
void setvalue(int value)
{
data=value;
}
friend void add(ABC,XYZ);
};
class ABC
{
int data;
public:
void setvalue(int value)
{
data=value;
}
friend void add(ABC,XYZ);
};
void add(XYZ obj1, ABC obj2)
{
cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data obj2.data;
cout << "\n";
}
int main()
{
XYZ X;
ABC A;
X.setvalue(5);
A.setvalue(50);
add(X,A);
return 0;
}
In particular, when I compile, g complains with the following log:
g -Wall -Wextra -Werror friend_function_add_data.cpp -o friend_function_add_data.o
friend_function_add_data.cpp: In function ‘void add(XYZ, ABC)’:
friend_function_add_data.cpp:33:86: error: ‘int XYZ::data’ is private within this context
33 | ut << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data obj2.data;
| ^~~~
friend_function_add_data.cpp:9:5: note: declared private here
9 | int data;
| ^~~~
friend_function_add_data.cpp:33:98: error: ‘int ABC::data’ is private within this context
33 | data values of XYZ and ABC objects using friend function = " << obj1.data obj2.data;
| ^~~~
friend_function_add_data.cpp:21:5: note: declared private here
21 | int data;
|
Since it was complaining about data
declared as private
, I changed the declaration to public by placing data
right after the public
statement for each class ABC
and XYZ
.
In this way g compiles without problems.
What I wonder is : is this the only correct way to handle this issue for this example? do you think it is just a mistake by the author himself?
This piece of code is taken from Balagurusamy's "OOP programming with C " (8th edition, page 124)
Edit: thanks Anoop for double checking! I realized I inverted the input arguments for each class ABC and XYZ, w.r.t. to the outer add function taking XYZ obj1 and ABC obj2. So it is written correctly on the book
CodePudding user response:
The problem is that while defining the function add
, the order of the two parameters named obj1
and obj2
is opposite to what it was in the friend declaration.
So to solve this, make sure that the order of the parameters match in the definition and the friend declaration as shown below:
class XYZ
{
public:
//other code here
friend void add(ABC,XYZ);
};
class ABC
{
public:
//other code here
friend void add(ABC,XYZ);
};
//ORDER OF PARAMETERS CHANGED TO MATCH WITH THE FRIEND DECLARATION
void add(ABC obj1, XYZ obj2)
{
cout << "Sum of data values of XYZ and ABC objects using friend function = " << obj1.data obj2.data;
cout << "\n";
}
int main()
{
XYZ X;
ABC A;
X.setvalue(5);
A.setvalue(50);
add(A,X); //ORDER OF ARGUMENTS CHANGED
}