I know below using C1::fn; will bring fn(…) functions declared in C1 to C2, but I want to know what’s the best practice for such using in design?
If fn() functions are not using C1 state, should I declare a helper class is the better way?
If fn functions are using C1 state, is using breaking encapsulation?
I appreciate if you can even mention some using cases in C++11. Like using the using Base::Base; constructor instead of calling it from derived member initializer?
class C1
{
//...
public:
int fn(int j) { ... }
double fn(double w) { ... }
void fn(const char * s) { ... }
};
class C2 : public C1
{
//...
public:
//...
using C1::fn;
double fn(double) { ... };
};
This
usingstatement doesn’t break encapsulation; it doesn’t expose anyprivatestate from C1 or prevent C1 maintaining its invariants. It’s purely a convenient way to expose whatever otherfnmembers C1 has – in this caseint fn(int)– so they can be considered when resolving calls. Think of it as functionally equivalent to……but better because you don’t have to manually add and remove functions to keep in sync with C1’s list of overloads.
If they’re not using C1 state, then they should be static or non-members. Helper classes are an ugly idea in my opinion. Namespaces are the normal method for grouping functionality in C++. I’m fully aware of Professor Lakos’s recommendations to use classes and understand all the arguments, and still disagree. Happy to run through it if the mention of helper classes was more than a passing thing for you.