Not being able to overload ++ operator

I am not being able to overload ++ operator.
I have written the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<iostream>
#include<conio.h>
using namespace std;

class A
{
      public:
             int nr;
             int dr;
             double val;
             A(int numerator = 0, int denominator = 1)
             {
                 nr = numerator;
                 dr = denominator;
                 val =(double)nr/dr;
                 cout<<"IN A CONSTRUCTOR"<<endl;
             }
             A operator++()
             {
               cout<<"1"<<endl;
               nr++;
               dr++;
               return(A(nr,dr));
             }
             virtual ~A()
             {
                 cout<<"IN A DESTRUCTOR"<<endl;
             }
             
                
};


ostream& operator<<(ostream& s,A* x)
{
   s<<x->nr<<"/"<<x->dr<<endl;
}


int main()
{
    A* obj = new A(3,2);
    
      cout<<obj<<endl;;  
      ++obj;
      cout<<obj<<endl;

    delete obj;
    getch();
    return 0;
}      


Please help me in finding the mistake in the above code.
closed account (Dy7SLyTq)
try using *this
You should be returning *this in the operator, but that isn't the problem. You are complicating things by using a pointer. See my edit to your code
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    A* obj = new A(3,2);
    
      cout<<obj<<endl;;  
      ++(*obj);//<--- HERE!
      cout<<obj<<endl;

    delete obj;
    getch();
    return 0;
}      
Last edited on
Better solution: don't use pointers/new unless you have to:

1
2
3
4
5
6
7
8
9
10
int main()
{
    A obj(3,2);

    cout << obj.nr << endl;
    ++obj;
    cout << obj.nr << endl;

    return 0;
}
This expression

++obj;

has nothing common with your overload operator. Here a pointer is increased. In fact this expression

++obj;

is equivalent to

obj = obj + sizeof( A );

that is there is the usual pointer arithmetic.
As @DTSCode above pointed out you need to return the instance of your class back from the operator function i.e. *this:

1
2
3
4
5
6
A& operator++()
{
   ++nr;
   ++dr;
   return *this;
}


HTH

Andrew
vlad from moscow wrote:
++obj;

is equivalent to

obj = obj + sizeof( A );

Not really. It is more equivalent to

obj = reinterpret_cast<A*>(reinterpret_cast<char*>(obj) + sizeof(A));

@Peter87


You are right. It is my typo.:)
Topic archived. No new replies allowed.