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.
Ask yourself: Does it have any meaning now, or may it have any meaning in the foreseable future, to call
f()with an object other thanm_Member1?If the answer is:
f()asm_Member1is an intrinsic part ofA.f(CMyClass &). Even if now you only usem_Member1, that is not an intrinsic property of the classes you handle.f(). There is always the option to change your mind (the change if fairly trivial, actually).Also note that a function
f()can call another functiong(CMyClass &), but not the other way around. So, depending on whatf()does, that may limit your options.