-5

I need an easy example. I know basic overloading of operators like +,-,*,<<,>> etc. And please help to complete my code.

#include<iostream>
using namespace std;
class XY
{
    int x,y;
public:
    XY()
    {
        x=0;y=0;
    }
    friend ostream &operator<<( ostream &output,const XY &D )
    {
         output << "X : " << D.x << " Y: " << D.y;
         return output;
    }
    friend istream &operator>>( istream  &input,XY &D )
    {
        input >> D.x >> D.y;
        return input;
    }

-> overloading starts here

    XY* operator ->() 
    {

    }    
};
int main()
{
    XY a;
    cout<<"Enter value of x & y  "<<endl;
    cin>>a;
    cout<<a;
    //way to access members
    cout<<a;
}
  • 3
    Noone is forcing you to overload this operator (if this is not school homework), thus it is rather strange that you are asking what to put there. First you should know for what reason you want to overload it.... – 463035818_is_not_an_ai Oct 07 '15 at 12:41
  • I read the title again, and maybe I got your point. I guess you misunderstood something. You do not have to overload anything to use the `operator->` to access members. Thats how its default implementation is working. You only have to overload it when you want to (mis-)use this operator to do anything else than accessing members of the class – 463035818_is_not_an_ai Oct 07 '15 at 12:48
  • That should be `XY* operator ->()`. Hint: there's only one `XY*` available for you to return in that function, and it's always available. – molbdnilo Oct 07 '15 at 12:48
  • You should access the members here with `a.x`, not with `->`. But `x` would need to be public. – interjay Oct 07 '15 at 12:58
  • that's what I need to do. a.x I can write as a->x. as I am not using a class using pointer, i can't use a->x(not sure) – Sourav Datta Oct 07 '15 at 13:01
  • What research have you done on how overloading `->` works? What exactly don't you understand from it? – Angew is no longer proud of SO Oct 07 '15 at 13:03
  • Possible duplicate of [Overloading member access operators ->, .\* (C++)](http://stackoverflow.com/questions/8777845/overloading-member-access-operators-c) – BlackDwarf Oct 07 '15 at 13:04
  • really speaking i haven't found anything helpful about -> overload. – Sourav Datta Oct 07 '15 at 13:05

1 Answers1

0

You can't make that code work as written since x and y are private.

If you make them public, this will work:

XY* operator ->() 
{
    return this;
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82