0

I have this link http://www.codingunit.com/unary-and-binary-operator-table. It says that pointer to member operator is a binary operator.

I have this code :

class test
{
public:
    int num;
    test(int j)
    {
        num=j;
    }
    test* operator->()
    {
        this->num;
    }
};

int main()
{
    test T(5);
    cout<<"Number is :"<<T->num;
}

As I know, non static member function of binary operator accepts one argument, but according to this program if I provide it one argument. It has an error, which says that test* operator ->(int x) should be test* operator ->(void) .

Hi-Angel
  • 4,933
  • 8
  • 63
  • 86
  • possible duplicate of [Overloading member access operators ->, .\* (C++)](http://stackoverflow.com/questions/8777845/overloading-member-access-operators-c) – m.s. Jun 06 '15 at 12:28

1 Answers1

0

To get the expected result, you need to change your program as follows:

test* operator->()
{
    return this;
}
};

int main()
{
test T(5);
cout<<"Number is :"<<T->num;
}

In your operator overloading function, you should return this pointer. Since your operator overloaded function for -> does not accept a parameter, so when you call it you don't need to pass a parameter value. So function call should be T->num;

Steephen
  • 14,645
  • 7
  • 40
  • 47
  • This works as well .I had the output .When i do **this->num** without using return .It works fine as well. –  Jun 06 '15 at 12:31
  • When you use `this->num`, you are not invoking overloaded function operator. Even you comment your operator over loaded function, if you use `this-> num` will work. – Steephen Jun 06 '15 at 12:32
  • Then what am i doing ? I mean if i am not invoking , then i shouldn't get the ouput as well? –  Jun 06 '15 at 12:34
  • I already added answered to your question in second line in my previous comment – Steephen Jun 06 '15 at 12:35