I'd like to weight in on a couple points:
Code:
Situation A:
i have a private member 'int x', and a method setX(int n){ x = n; }.
within a private member 'do_something(void)' i need to change the value of x...do i use setX() or simply x = a_number; ?
You could also do something as such:
Code:
class Foo {
int x_;
int& x() { return x_; }
public:
Foo();
int setX(int);
};
Now inside of your other member functions you can do things such as:
Code:
int Foo::setX(int j) {
x() = j;
return x();
}
Now returning a non const reference has one draw back over the set function method. There is no way to range check the value. So say x can only range from 0 to 100, using the non const reference method the user could set it to 101 where in the set function method you can ensure that value never gets assigned.
However by making it private (or even protected if you want derived classes to be able to use it) you make it so that you can use it but no one else. It can make it easier for you when you are writing your other functions.
I also note that most people write their set functions with a void return type. Please for the love of sake return the value so that I can chain them together if I so choose.
On exceptions:
I think one reason people don't use them a lot is because they bulker then return value errors. They can also make it harder to read the code if you are dealing with a lot of possible thrown errors. Another difficulty is having to know the type name of the object being thrown.
As a general rule I like exceptions even when it can be a pain in the arse to use. I will however quote someone with far more knowledge on the subject then I:
Bjarne Stroustrup: C++ Programming Lnguage 3rd Edition page 386
Use exceptions for error handling
Don't use exceptions where more local control structures will suffice
Edit: I'm note a huge fan of the setX(), getX() methods. I much prefer the single name overloaded method:
Code:
class Foo {
int x_;
public:
int x() const { return x_; }
int x(int j) { /* insert range checking */ return x_ = j;}
};