I have read a lot of materials regarding preferring returning values from function like this:
some_class func();
over getting output by passing it by reference like this:
void func(some_class& input);
I have found little information regarding whether similar rule applies to class private member methods though. Suppose I have a class A
with members a
, b
and c
, where variables a
and b
are set via the constructor, and c
is calculated based on a
and b
. One may design such a class in the following ways:
class A
{
A(const Class1& x, const Class2& y) : a(x), b(y) { outer_funct() };
private:
// option 1: calculate a in some outer function like this: c = calc_c();
// a and b values are only read within the method's body:
Class3 calc_c() const;
// option 2: calculate a inside calc_c();
// a and b values are only read within the method's body:
void calc_c();
void outer_funct()
{
// option 1:
c = calc_c();
// option 2:
calc_c();
}
Class1 a;
Class2 b;
Class3 c;
};
In reality c
would be an object, whose value depends on more than ten member variables - that is why I don't consider having a stand-alone helper function that takes the variables needed for calculating c
by const reference.
I am weighing pros and cons of both approaches.
What speaks to me about the option 1 is that it shows my intent, which is that calling calc_c()
should result in modyfing only one variable, and const qualifier prevents side effects. On the other hand, writing the method in such a way may make someone think it could be used for setting other member variables of Class3
too, whereas it should only be used to set c
- I have doubts whether relying on commenting the functions is a good solution to prevent that.
Option 2 in turn looks appealing beacuse it doesn't mislead the reader in the way described above. On the other hand, there is no syntactic hint regarding which variables should be or should not be modified within this function, so it may be harder to maintain the class invariants and track down bugs.
I'd like to know if there are some other considerations speaking for one of the options that I cannot see. Is it a matter of taste in the end, or is there something more to it that would favor one of the options as "better"?