When do I make a function a class member function in C++?

Viewed 231

I am fairly new to programming and am confused over when I should make a function a member function of a class or just use member getter functions to access the private members of the class. I can do it either way I think.

Consider the following:

#include <iostream>
#include <string>
using namespace std;

class Person
{  
  string name;
  int age;
public:
  Person()
    : name("James"), age(30)
  {};
  void Print();
  string GetName(Person& person) { return name;};
  int GetAge(Person&) { return age;};
};

void Person::Print() // member function
{
 cout << "Using member function: " << name << ", " << age << endl;
}

void Print(Person& person) // non-member function 
{
 cout << "Using non-member function: " << person.GetName(person) << ", " << person.GetAge(person) << endl;
}

int main() 
{
Person test_person; //default constructor
test_person.Print(); // member function
Print(test_person); // non-member function

return 0;
}

The output is the same for both the member function Person::Print() or the non-member function Print() i.e. the program produces:

Using member function: James, 30
Using non-member function: James, 30

You can clearly then write a non-member function that uses member getter functions to access private members of the class so you can do it either way.

It seems to me like making Print() a member function of class Person is the way to go since the function is clearly specific to the class and its private data and will probably want to be used by someone else if they use the class.

Is that right? What else should I be considering?

3 Answers

Your code is similar to the codes below:

private:
 string name;
 int age;

these attributes is only access inside the class object. You can not call it from outside the object, And you only use geter(), seter() to get, set value for the object.

If you use the public attributes, there is similar to struct structure on C/C++

I think you may want to consider taking another look on access modifiers. You can not modify private or protected data members of a class. Thus you need member functions for them.

Prefer member functions over non-member functions. Suppose you change the name from Print to Log and you forget the name. For most IDE, a member function could be easily looked up by typing "." then find the right one, while non-member function will require several keystrokes of guessing before finding the right one.

I will also say member functions are more intuitive to use for many cases.

Implementing both are not considered bad practice as well. For example, for std::vector v, there is member function v.size() as well as the general purpose non-member function std::size(v)

Related