What is overloading++

All QuestionsCategory: Cpp LanguageWhat is overloading++
Anonymous asked 3 years ago
1 Answers
Anonymous answered 3 years ago

As only one operand is involved while overloading unary operators, the operand(object) itself invokes the member function and no arguments are applicable to the function.
For pre-increment operator++ is executed without any arguments
For eg:- If ++t1 is requested t1.operator++() will be invoked

MyTime& operator++()
{     
    ++this->mm;       //TODO:tm>60
    return *this;   
}

And for post-increment, a dummy integer is passed as an argument. There is no sign of this dummy integer at all. This is just to differentiate pre and post-operation since two functions at the same scope can’t have the same name and same parameters.

MyTime operator++(int)
{     
    MyTime orig(*this);
    this->mm++;              //TODO:tm>60
    return orig;   
}



Complete Code


#include<iostream>
class MyTime {
int hh;
int mm;

public:
MyTime():hh(0),mm(0) { }
MyTime(int h, int m) : hh(h), mm(m) {}
MyTime(const MyTime &ref) : hh(ref.hh), mm(ref.mm) {}
MyTime& operator++() {
++mm; // TODO: mm > 60
return *this;
}
MyTime operator++(int dummy) {
MyTime orig(*this);
++mm; // TODO: mm > 60
return orig;
}

void display() const { std::cout << hh << ":" << mm << "\n"; }
};
int main() {
MyTime t1(10,20);
MyTime t2(1,15);

++t1;
(++t2).display();
// ++t1 + t2

MyTime t3(5,40);
MyTime t4;
t4 = t3++; //t3.operator++(int)
// (t3++).display()
// t1 + t3++

return 0;
}