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?