Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a class named "data" in which i perform some work with files where i have 4 private variables.I want to use this data in another class named "level".How can i use those private variables in another class?

What I have tried:

I've tried getting acces with an object by returning the value via a function but it says something about the "<< operator",i assume that it has something to do with overloading the "<<" but i don't know how to do that and don't know if it works between classes
Posted
Updated 9-Mar-17 10:01am
Comments
[no name] 9-Mar-17 13:56pm    
You use public properties.
Member 13049206 9-Mar-17 14:04pm    
What do you mean
[no name] 9-Mar-17 14:27pm    
I mean exactly what I said.
Richard MacCutchan 9-Mar-17 14:33pm    
"it says something about"
So you want us to guess what "it" is, and what "it" said, and when or where? Why not show the actual code, and the exact error message(s), and people may have some clue as to what you are talking about?

 
Share this answer
 
Comments
CPallini 9-Mar-17 16:09pm    
A savy suggestion.
5.
Maciej Los 9-Mar-17 16:14pm    
Thank you, Carlo.
An obvious solution, already suggested, is implementing getter and setter (if you new both read and write access to the variables) methods in class data and then use it in class level.
C++
#include <iostream>
using namespace std;

class data
{
  int d; // the private variable d
public:
  data(int d):d(d){}

  int get_d() const {return d;} // grant read access to d
  void set_d(int d){this->d = d;} // grant write access to d
};


class level
{
public:
  // read access to d
  void show_d(const data & dt)
  {
    cout << dt.get_d() << endl;
  }
  // write access to d
  void inc_d(data & dt)
  {
    dt.set_d( dt.get_d() + 1);
  }
};

int main()
{
  data dt(5);

  level lv;
  lv.show_d( dt);
  lv.inc_d(dt);
  lv.show_d(dt);
}
This way, however, the private variable is exposed (via getter and setter) to all the data class consumers.

Another approach uses the friend[^] specifier to grant to level class full access to all data class members.
C++
#include <iostream>
using namespace std;

class level; // forward declaration of level class
class data
{
  int d; // the private variable d
public:
  data(int d):d(d){}
  friend class level; // grant to level class full access to private members
};


class level
{
public:
  // read access to d
  void show_d(const data & dt)
  {
    cout << dt.d << endl;
  }
  // write access to d
  void inc_d(data & dt)
  {
    ++dt.d;
  }
};

int main()
{
  data dt(5);

  level lv;
  lv.show_d( dt);
  lv.inc_d(dt);
  lv.show_d(dt);
}
 
Share this answer
 
v3
Comments
Maciej Los 9-Mar-17 16:14pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900