Should I be placing every variable inside classes as private
or protected? Sometimes it's annoying to make an accessor
for each private/protected variable but I am used to it. I am
also trying to figure out if it is possible setting a private or
protected variable through file streaming for example:
#include <iostream>
#include <fstream>
using namespace std;
class Test
{
public:
inline void setVal(int temp) {val = temp;}
inline int getVal() const {return val;}
private:
int val;
protected:
};
int main()
{
Test testMain;
ifstream file("test.txt"); //Say I have the number(15) in the file and I want to assign it to the private variable
file >> ?; //using the testMain object. I tried a lot of ways but they do not work.
file.close();
return 0;
}
I already searched google for this and found nothing.
Last edited by zodiac976 on Mon Jun 29, 2009 8:13 pm, edited 1 time in total.
So I would have to make accessors for it because
the only way to access them is through a classes
methods anyways? Why would I put variables as
private with no accessor?
So I would have to make accessors for it because
the only way to access them is through a classes
methods anyways?
Is this a question? If you have private variables that need to be accessed by another class, then the most proper implementation would be to have accessor functions. However, this is not required. You need to make a decision whether or not something should be private/public. Base that decision on what it needs to accomplish, rather than forcing strict OOP design methodology.
Why would I put variables as
private with no accessor?
If they are only going to be used by the class they are members of. I'd say that gives you the most reason to make them private.
Well normally I make a class and variables I want to use for
it and make accessors for each one but if I happen to need
them for another class I just use inheritance.
zodiac976 wrote:Well normally I make a class and variables I want to use for
it and make accessors for each one but if I happen to need
them for another class I just use inheritance.
Wait.. what? You use accessors to access a class's variables from within itself, and use inheritance to access them from another class?