0

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)

3
  • 3
    You can't overload operators on non-class types. Commented Jun 3, 2014 at 21:36
  • 1
    ^ specifically a pointer Commented Jun 3, 2014 at 21:36
  • 1
    ++I already does something, it increments the pointer. Like it should. Commented Jun 3, 2014 at 21:43

3 Answers 3

6

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

Item I(5);
++I;
Sign up to request clarification or add additional context in comments.

Comments

2

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

I->operator++();

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.