Typically, it is good practice to give as little access as possible, especially if you're just going to let others use your code.
The person using your class may know how to use a member, but they could inadvertently do something invalid with it.
If you want to allow access to see the value of something but not modify it, you can use a 'getter'
If you want to allow access to set the value of something but have control over how it is modified, you can use a 'setter'
Both of those are with member functions.
Even the standard library makes use of these, like doing string.length(), instead of allowing direct modification of that variable, since doing so in the wrong context could have quite negative results.
Every API/library I've used has used setter/getter methods in some form to allow access/modification of data in a controlled way.
1 2 3 4 5 6 7 8 9 10 11 12
|
class MyClass
{
public:
MyClass();
~MyClass();
int getInt();
void setInt(int value);
private:
int myInt;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include "MyClass.h"
MyClass::MyClass()
{
...
}
MyClass::~MyClass()
{
...
}
void MyClass::setInt(int value)
{
myInt = value;
}
int MyClass::getInt()
{
return myInt;
}
|
If you want to make it nicer, use const correctness
MyClass.h
1 2 3 4
|
...
void setInt(const int &value);
int getInt() const;
...
|
MyClass.cpp
1 2 3 4 5 6 7 8 9 10
|
...
void MyClass::setInt(const int &value)
{
myInt = value;
}
int MyClass::getInt() const
{
return myInt;
}
|