Home > database >  Why can't I access private functions of class Box in operator<<?
Why can't I access private functions of class Box in operator<<?

Time:06-16

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

Working demo

CodePudding user response:

You can´t access them because they are private of course...

If you want to access them without making them public then you should create a member function that return those private members here an example

getLmember(){
 return l;
}

or make them public

  • Related