confused with below program for friend class use, please help me to solve that
#include <iostream>
using namespace std;
class square;
class rect {
public :
rect(int w = 0, int h = 0) : width(w), height(h), volume(w*h) {}
void set_data(square &);
int get_width(void)
{
return width;
}
int get_height(void)
{
return height;
}
int get_volume(void);
private :
int width;
int height;
int volume;
};
class square {
public :
square(int w = 0, int h = 0) : width(w), height(h), volume(w*h) {}
int width;
int height;
int get_volume(void);
**// friend class rect;**
private :
int volume;
};
void rect :: set_data(square &s)
{
width = s.width; *// the variables of rect class are private and it shud not allow to change as i have commented "//friend class rect;" the sentence in square class.*
height = s.height;
}
int rect :: get_volume(void)
{
return volume;
}
int square :: get_volume(void)
{
return volume;
}
int main()
{
rect r(5,10);
cout<<r.get_volume()<<endl;
square s(2,2);
cout<<s.get_volume()<<endl;
cout<<endl;
cout<<endl;
r.set_data(s); *// accessing the private members of the rect class through object of square class*
cout<<"new width : "<<r.get_width()<<endl;
cout<<"new height : "<<r.get_height()<<endl;
cout<<r.get_volume()<<endl;
return 0;
}
As per friend guide lines if we use friend class then it can able to access and modify the private members of its friend class so even though i have commented "//friend class rect;" in square class why i am seeing that the members of rect class has been changed by square class by "r.set_data(s);" this function In normal condition as per my understanding the private variables of a class can be changed only if it is friend class(so in below output new width and new height should not be changed as I have commented "//friend class rect;" but even though it is commented I am seeing changes of variables of rect class by set_data function so what is the need to use friend class if private members are changed simply by passing other object to any function.
output of the program :
50
4
new width : 2
new height : 2
50