Non-member function vs member function

Which is preferred for something like this in general?
1
2
3
4
5
  bool isTooYoung (Person* person) {return person->Age() < 10;}

or

  bool Person::isTooYoung () const {return age < 10;}


Should ANY function that has an object as parameter be made into a member function of that class instead? Is that generally the best programming practice, while making such a function global considered questionable practice? Efficiency-wise, is there a difference?
Last edited on
Depends, if isTooYoung() uses member variables from Person, then certainly use make it a member function. If it doesn't but only applies in context of person like this:
1
2
3
4
5
6
7
8
9
10
11
class person
{
    //no member variables
    public:
    bool ifTooYoung()
    {
         bool check; 
         check=CheckForYoungness();
         return check;
     }
};

Then I would also recommend it be a member function (for simplicity, and readability).

However, if isTooYoung requires multiple persons (for whatever reason), then the only option is a global function.

In your particular example, member function all the way.

EDIT: to answer your edit, yes always go for member functions, it's far easier and if you ever expand your hierarchy (class Population public:Person) it'll carry over with no hassle.
Last edited on
So this function of mine:
1
2
3
4
5
6
7
8
9
10
std::string firstName (const Person* person) {
	const std::string digits = "0123456789";  // If her name is something like Amina Rashad 12 
                // (due to other Amina Rashad's existing), then return the full name.  So first check if her last character is a digit.
	const char lastCharacter = person->Name().back();
	int pos = digits.find (lastCharacter);
	if (pos < digits.length())
		return person->Name();
	pos = person->Name().find (" ");  // Else, her name is normal so take the token before the first blank, if any (this might have to be modified if her name is something like Mary Ann Singh, or Dirty Diana).
		return person->Name().substr (0, pos);
}


should be a member function, right? As a result, my Person class will have literally hundreds of member functions. But I shall change each one.
Last edited on
If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions. - Scott Meyers in Dr. Dobb's

http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197?pgno=1
Ah! A different answer. Let me read this article now before I decide to change my above-mentioned function std::string firstName (const Person* person) to a member function.
Last edited on
Topic archived. No new replies allowed.