Search code examples
c++classprivateoperator-keywordiostream

Why can't I access private members of class Box in operator<<?


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;
    }

Solution

  • 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;
    }
    
    

    Working demo