jasonkim
jasonkim

Reputation: 706

Call private member within the method belonging to the class itself

I encountered this problem when implementing a class:

class Cell {
     bool isAlive;
     int numNeighbours;
     //...omit irrelavent private members



     public:
         Cell();  // Default constructor
         ~Cell(); // Destructor


      void setLiving();   

     ....         
    };
    void Cell::setLiving(){
         isAlive=true;
       }


 class Grid{...
  friend std::ostream& ::operator(std::ostream& out, const Grid &g);
  };//...omit

 std::ostream& ::operator<<(std::ostream &out, const Grid &g){
 int i,j;
 for(i=0;i<g.gridSize;i++){
   for(j=0;j<g.gridSize;j++){
         if(**g.theGrid[i][j].isAliv*e*) out<<"X";
         else out<<"_";
    }
    out<<endl;
   }
    return out;
  }

The complier said that "isAlive" is a private member so I can't call it that way I think the problem is at "g.theGrid[i][j].isAlive" I tried to friend class Grid but it didnt help

Upvotes: 0

Views: 258

Answers (4)

kbyrd
kbyrd

Reputation: 3351

This line

if(**g.theGrid[i][j].isAlive) out<<"X"

Is accessing the private member 'isAlive'. I assume theGrid is a two dimensional array of Cell objects. You need a getLiving() method defined. Then use it here.

Upvotes: 0

joy
joy

Reputation: 1569

isAlive is private, declare it as public...

EDIT1:

class Cell {
public:
   bool isAlive;

Update:

  • private members of a class are accessible only from within other members of the same class or from their friends.
  • protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
  • Finally, public members are accessible from anywhere where the object is visible.

Upvotes: -1

Crazy Bear
Crazy Bear

Reputation: 101

The class member isAlive is private, so the operator didn't have the right to access it, you need to put a friend declaration in the body of Cell's definition.

class Cell {
friend std::ostream& operator<<(std::ostream&, const Cell&);
// ...

};

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129764

You mentioned operator<< — it's most likely a free function, so it needs to be declared as friend to be able to access private members.

class Cell {
    friend std::ostream& operator<<(std::ostream&, const Grid&);
    // ...
};

Upvotes: 4

Related Questions