I read multiple times that when a member function only uses API of class it is member of, then it should be made free standing and put in to same namespace, for example, bad practice:
namespace A
{
class Foo
{
public:
void printA() const { std::cout << a << std::endl;}
void printB() const { std::cout << b << std::endl;}
void printAandB() const
{
printA();
printB();
}
private:
constexpr int a = 1;
constexpr int b = 2;
};
}
good practice:
namespace A
{
class Foo
{
public:
void printA() const { std::cout << a << std::endl;}
void printB() const { std::cout << b << std::endl;}
private:
constexpr int a = 1;
constexpr int b = 2;
};
//now free standing.
inline void printAandB(const Foo & foo)
{
foo.printA();
foo.printB();
}
}
Now my question is, what if Foo is inhereting from some other class:
namespace A
{
class Foo final : public InterfaceFoo
{
....
};
}
, and I am using a base pointer, then printAandB can't be used, I could just make printAandB member again or make another printAandB which accepts a smart pointer to the base class:
inline void printAandB(std::shared_ptr<InterfaceFoo> foo)
{
foo->printA();
foo->printB();
}
. But I am not sure, what is the better choice? Maybe there is an alternative.
std::shared_ptr
in a function that only interacts with the pointed-to object, just take aInterfaceFoo &
printAandB
doesn't need to participate in the ownership of theInterfaceFoo
, it doesn't store it anywhere. If the caller has astd::shared_ptr<InterfaceFoo>
, they can just dereference it into the call