Here's a question that comes up again and again in C++ class implementation. I'm curious about what people's thoughts are here. Which code do you prefer and why?
class A
{
public:
/* Constructors, Destructors, Public interface functions, etc. */
void publicCall(void);
private:
void f(void);
CMyClass m_Member1;
};
with
void A::publicCall(void)
{
f();
}
void A::f(void)
{
// do some stuff populating m_Member1
}
Or the alternative:
class A
{
public:
/* Constructors, Destructors, Public interface functions, etc. */
void publicCall(void);
private:
void f(CMyClass &x);
CMyClass m_Member1;
};
with
void A::publicCall(void)
{
f(m_Member1);
}
void A::f(CMyClass &x)
{
// do some stuff to populate x,
// locally masking the fact that it's really m_Member1
}
I think I always prefer the second one because then f
can then operate on any instance of CMyClass
but, that said, I have lots of code where the first is perfectly valid since f
will only ever operate on m_Member1
and I'm really breaking it into two functions to make the code more readable.
Yes, this is more of a discussion question than an "answer" question, but I'm more interested in the reasoning. I'll mark as an answer a response that gives good reasoning or a good criterion.
Also, keep in mind that this is just a toy example. The class will be bigger than this in reality and thus organization is important.