PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

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

 July 08, 2022     c++, class, iostream, operator-keyword, private     No comments   

Issue

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



Answered By - Anoop Rana
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing