"Rule of thumb" for free function vs member function

901 Views Asked by At

There is a popular guideline (Scott Meyers, Klaus Iglberger, ect) that I recently put more thought into, which is basically prefer non-member (free) functions to member functions. I'm noticing that I can indeed actually pull most of my member functions outside, but I'm having a hard time figuring out when that's actually what I should do.

Here is a simple example, a function that prints a vector of strings (a private data member) to console in some formatted way:

void list::print() const {
    std::cout << "Printing list -> " << list_.size() << " entries.\n";
    std::cout << "--- START OF LIST ---\n";
    for (const auto &s : list_) {
        std::cout << s.size() << " : " << s << '\n';
    }
    std::cout << "--- END OF LIST ---\n";
}

I find it difficult to decide in simple cases like this, it seems to me that in the short term the member function is a bit more elegant whilst a free function can adapt to multiple objects as a program gets larger. Does anyone have some kind of rule of thumb to help decide? Am I just overthinking this? Thanks.

0

There are 0 best solutions below