Why aren't the member functions called by value like the normal functions in c++?

106 Views Asked by At

In c++, the changes done to the argument inside a function aren't reflected in the actual variable if the return value of function is void, but that's not the case with the member functions where we can
see the changes happening permanently.

 #include<iostream>
 using namespace std;

 class Student {
 
 public:
 int age;
 float marks;
 Student()
  {
    cout << "call by default";
  }
 void ageInc()
  {
    age = age + 1;
  }
 };

 int main()
 {
  Student s;

   s.age = 34;
   cout << s.age << endl;

   s.ageInc();
   cout << s.age << endl;
   return 0;
 }
2

There are 2 best solutions below

1
dspeyer On

Because you're not changing an argument. Your example function takes no arguments. You're changing a member variable.

You could think of all members of the object as being automatic passed-by-reference parameters, but this isn't how C++ encourages you to think of them.

0
Remy Lebeau On

In c++, the changes done to the argument inside a function aren't reflected in the actual variable if the return value of function is void

Changes to an argument's value has nothing at all to do with a function's return type. A void function can quite easily make changes to its arguments. Whether or not those changes are reflected back to the caller has to do with whether the argument is passed by pointer/reference or not.

but that's not the case with the member functions where we can see the changes happening permanently.

A non-static class method receives a hidden this pointer to the object it is being called on. When the method accesses a non-static member of its owning class, it is using that this pointer to access the member. So any changes made to the member are done directly to the mmeber.

Your example is roughly equivalent to the following behind the scenes:

#include <iostream>
using namespace std;

struct Student {
    int age;
    float marks;
};

Student_ctr(Student* const this)
{
    cout << "call by default";
}

Student_dtr(Student* const this) {}

void Student_ageInc(Student* const this)
{
    this->age = this->age + 1;
}

int main()
{
    Student s;
    Student_ctr(&s);

    s.age = 34;
    cout << s.age << endl;

    Student_ageInc(&s);
    cout << s.age << endl;

    Student_dtr(&s);
    return 0;
}