Why can't I access private functions of class Box
in ostream& operator<<(ostream& out, const Box& B){cout << B.l << " " << B.b << " " << B.h << endl; }
?
#include<bits/stdc .h>
using namespace std;
class Box{
int l, b, h;
public:
Box(){
l=0;
b=0;
h=0;
}
Box(int length, int breadth, int height){
l=length;
b=breadth;
h=height;
}
bool operator < (Box &B){
if(l < B.l)return 1;
else if(b < B.b && l==B.l)return 1;
else if(h< B.h && b== B.b && l==B.l)return 1;
else return 0;
}
};
ostream& operator <<(ostream& out, const Box& B){
cout << B.l << " " << B.b << " " << B.h ;
return out;
}
CodePudding user response:
The problem is that you don't have any friend declaration for the overloaded operator<<
and since l
, b
and h
are private
they can't be accessed from inside the overloaded operator<<
.
To solve this you can just provide a friend declaration for operator<<
as shown below:
class Box{
int l, b, h;
//other code here as before
//--vvvvvv----------------------------------------->friend declaration added here
friend ostream& operator <<(ostream& out, const Box& B);
};
//definition same as before
ostream& operator <<(ostream& out, const Box& B){
cout << B.l << " " << B.b << " " << B.h ;
return out;
}
CodePudding user response:
You can implement the operator overloading in two ways:
Member function
If it is a member function, then any instance of Box, can access the private members of Box class.
For e.g., for operator "bool operator < (Box& b)", when you call b1 < b2 (where b1 and b2 are instances of Box), then you can directly access private members of both b1 and b2 in the "operator <" implementation.
Non-member function
Non-member functions, by default, cannot access the privates of a class.
So, either the non-member overloaded operator has to be declared as a friend of Box class or you need to define public functions for the private members which will be accessed in this non-member overloaded operator.
You can also check the discussion here, which clearly explains when an overloaded operator can be implemented either as a member or a non-member function: Operator overloading : member function vs. non-member function?