What's the point? Can't you just make all the class members public instead of going through all that crap?
Printable View
What's the point? Can't you just make all the class members public instead of going through all that crap?
well part of the idea behind having memeber variables private, is so that are protected from being messed with. If they were public, then anyone could get in and mess with the variables. But by having them private, the only way to access or manipulate them is through pre-written member functions. It is the idea of "black box".
Van
You can't change them later if you make them public.
As an illustrative example, let's say you have a square class, with an area member function. If you had this as a public member, you would need to always store the area as a member, but if you make it a function, then you are at liberty to either keep it as data and then have the the area function return it, or you are free to simply compute it from the length.
Essentially, the more implementation you hide, the more implementation you can change. If you don't think of a program totally as it exists now, but rather how flexible it is to change in the future, things like accessors make a big difference.
If you use member functions then it is impossible to do evil things like taking the address of the member variable etc.
It's also easier to extend the code.
Example:
Now in Object version 2.0, the number stored should be a complex<double> instead. Now it is very easy to extend the code, without having to change the code that uses the class:Code:class Object
{
public:
....
double getNum();
double setNum(double num);
private:
....
double num;
};
In other words: It is better.Code:class Object
{
public:
....
double getNum()
{
if (num.imag() != 0) throw std::exception("bad num");
return num.real();
}
double setNum(double num);
private:
....
complex<double> num;
};
One solution is to use this header.
Use it if you like, but it is not extremely useful.