0

I am very new to CPP and I came across operator overloading today. It was a bit confusing for me at first and then I kinda caught up. But still, I have doubts about this specific line, Test operator + (Test arg), where Test is the class name and the parameters inside the parenthesis should be my test1 object and tets 2 object. I just don't get it, how this->a gives the exact value of test.a. Here is my code and it works as expected.

#include<iostream>
using namespace std;

class Test{
    
    public:
    int a;
    
    void getValue(int n){
        std::cout << "Enter the value for"<<n<<":" << std::endl;
        std::cin >> a;
    }
    
    Test operator + (Test arg)
    {
        Test test3;
        test3.a=a + arg.a;
        return test3;
    }
    
};

int main(){
    Test test1,test2,test3;
    
    test1.getValue(1);
    test2.getValue(2);
  
  test3=test1+test2;
  cout<<"The value in test3 is:"<<test3.a;
    
}
Devil King
  • 13
  • 1
  • 1
    `I am very new to CPP` so do not try do operator overloading yet. Master basic first before doing that, then it will be simple to understand this feature. – Marek R Nov 08 '20 at 10:56
  • In *any* non-static member function of a class, `this` is a pointer to the object, and `this->a` is the member of that object named `a` (assuming there is one, of course). So `a.some_member_function()` passes the address of `a` via the `this` pointer. The member-form of `operator+()` you are using works the same way. `test1 + test2` is translated as `test1.operator+(test2)` and, in the body of the `operator+()` function `this` points at `test1`. It works that way because the C++ standard requires it to work that way, and compilers do whatever is needed to make it work that way. – Peter Nov 08 '20 at 11:06
  • @Peter, thanks man. Now I get it – Devil King Nov 08 '20 at 11:09
  • @MarekR, sorry but I just wanted to try it. Btw the basics that I studied, it was nothing special. It just showed me the way how to do it but I want to know how it happened. Is there any source you want to recommend for in-depth knowledge? – Devil King Nov 08 '20 at 11:13
  • the duplicate is one of the best sources on operator overloading I am aware of and cppref for a more compact overview of the most important stuff https://en.cppreference.com/w/cpp/language/operators – 463035818_is_not_an_ai Nov 08 '20 at 11:30

0 Answers0