#include <iostream>
using namespace std;
class Counter {
private:
int count;
public:
Counter() : count(0) {} // Constructor to initialize count
// Overloading unary ++ operator (prefix)
Counter& operator++() {
++count;
return *this; // Return reference to the object
}
void display() {
cout << “Count: ” << count << endl;
}
};
int main() {
Counter c1;
cout << “Initial count: “;
c1.display();
// Pre-increment
++c1; // Same as c1.operator++()
cout << “After pre-increment: “;
c1.display();
return 0;
}
Output:
Initial count: Count: 0
After pre-increment: Count: 1
Here’s a step-by-step explanation of the code:
1. Header and Namespace:
- #include <iostream>: Includes the iostream header for input/output operations.
- using namespace std;: Brings the std namespace into scope for convenient use of elements like cout, cin, and endl.
2. Counter Class:
- class Counter { … }: Defines a class named Counter to represent a counter object.
- private: int count;: Private member variable to store the count value.
- public: Counter() : count(0) {}: Default constructor to initialize count to 0.
- Counter& operator++() { … };: Overloads the unary ++ operator (prefix) to increment the count.
- void display() { … };: Member function to display the current count.
3. Main Function:
- int main() { … }: The program’s entry point.
- Counter c1;: Creates an object of the Counter class.
- cout << “Initial count: “; c1.display();: Prints the initial count.
- ++c1;: Pre-increments the count using the overloaded ++ operator.
- cout << “After pre-increment: “; c1.display();: Prints the count after incrementing.
- return 0;: Indicates successful program termination.
4. Operator Overloading Key Points:
- Operator Function Name: The overloaded ++ operator function is named operator++().
- Return Type: It returns a reference to the Counter object (Counter&), allowing for chained operations like ++c1++.
- Implementation: The function increments the count member and returns *this, a reference to the current object.