- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Increment ++ and Decrement -- Operator Overloading in C++
The increment (++) and decrement (--) operators area unit 2 necessary unary operators available in C++. Following example explain how increment (++) operator can be overloaded for prefix as well as postfix usage. Similar way, you can overload operator (--).
Example
#include <iostream> using namespace std; class Time { private: int hours; int minutes; public: Time(int h, int m) { hours = h; minutes = m; } void display() { cout << "H: " << hours << " M:" << minutes <<endl; } // overload prefix ++ operator Time operator++ () { ++minutes; // increment current object if(minutes >= 60) { ++hours; minutes -= 60; } return Time(hours, minutes); } // overload postfix ++ operator Time operator++( int ) { Time T(hours, minutes); // increment current object ++minutes; if(minutes >= 60) { ++hours; minutes -= 60; } // return old original value return T; } }; int main() { Time T1(11, 59), T2(10,40); ++T1; T1.display(); ++T1; T1.display(); T2++; T2.display(); T2++; T2.display(); return 0; }
Output
This gives the result −
H: 12 M:0 H: 12 M:1 H: 10 M:41 H: 10 M:42
Advertisements