user3704771
user3704771

Reputation: 7

c++ pointer: overload operator++

I tried find anything about overload operator ++ for pointer, but without results.

There is my code.

struct Item
{
    int amount;
    Item(int a){ this->amount = a; };
    Item& operator++()
    { 
       this->amount++; 
       return *this;
    };
};


int main()
{

    Item *I = new Item(5);

    ++*I;

    return 0;
}

Is there any options that a could write only in main function

++I;

(sorry about my English)

Upvotes: 0

Views: 947

Answers (3)

Filip Roséen
Filip Roséen

Reputation: 63902

No, you cannot overload operators for pointer types.

When defining your own operator++ the first argument to the function must be of class- or enumeration-type, as specified in [over.inc]p1 in the C++ Standard:

The user-defined function called operator++ implements the prefix and postfix ++ operator. If this function is a member function with no parameters, or a non-member function with one parameter of class or enumeration type, it defines the prefix increment operator ++ for objects of that type.


But I really really want to call operator++ without having to explicitly write *ptr...

And you can, but it's not the prettiest looking line of code:

ptr->operator++ (); // call member function `operator++`

Note: Instead of doing Item *I = new Item (5); ++*I, consider using just Item I (5); ++I, there's no need to use pointers in your snippet.

Upvotes: 1

vsoftco
vsoftco

Reputation: 56577

You can manually write (if you REALLY want to use a pointer)

I->operator++();

Upvotes: 2

David G
David G

Reputation: 96875

Just don't use a pointer (there's no need for it anyway):

Item I(5);
++I;

Upvotes: 6

Related Questions