Thread: Overload pre and post increment

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    18

    Overload pre and post increment

    Hi all,

    I just reached the overloading chapter, amazing and confusing .
    so i tried to overload the pre and post increment operations. So i did the following:

    Simple class:
    Code:
    class Counter {
    public:
        Counter() : val(0) {};
        Counter(int ival) : val(ival) {};
        Counter(const Counter& rhs);
    
    
        int GetVal() const { return val; }
        void SetVal(int v) { val = v; }
    
    
        const Counter operator++();
        const Counter operator++(int dummy);
    private:
        int val;
    };
    Pre-increment:
    Code:
    const Counter Counter::operator++() {
        cout << "pre increment called" << std::endl;
        ++val;
        return *this;
    }
    Post-increment:
    Code:
    const Counter Counter::operator++(int dummy) {
        cout << "post increment called" << std::endl;
        Counter temp(*this);
        ++val;
        return temp;
    }
    using both of them :
    Code:
    Counter c(1);
    Counter pre = ++c;
    Counter post = c++;
    i printed the results. they are fine and correct.
    the 2 functions are similar except the parameter "dummy".
    my question : how is ++c or c++ calling the right function ?

    why is ++c calling the function without input parameter? and c++ calling the function with the input parameter?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,498
    The dummy thing is only there to distinguish the pre and post versions from being otherwise identical definitions.
    Increment/decrement operators - cppreference.com
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with Pre and Post Increment !
    By thebenman in forum C Programming
    Replies: 25
    Last Post: 10-30-2014, 01:05 AM
  2. Post Increment an Pre Increment operators in c++
    By anil_ in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2011, 08:27 PM
  3. pre & post increment need help
    By zing_foru in forum C Programming
    Replies: 6
    Last Post: 10-09-2009, 12:14 PM
  4. post vs pre increment
    By xddxogm3 in forum C Programming
    Replies: 13
    Last Post: 03-19-2004, 05:07 PM
  5. Post increment and pre increment help
    By noob2c in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2003, 03:03 AM

Tags for this Thread