×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ program to overload unary pre-increment operator and provide support for assignment operator (=)

Learn: How to overload unary pre-increment operator in C++, which will return an object so that we can use assignment operator (=) to store the incremented value in it.

Read: operator overloading and its rules

We have already discussed how to overload pre-increment operator in C++? But that program does not support assignment operator i.e. if we want to store the value of incremented object in another object, we cannot.

In this article we will understand, how to overload pre- increment operator and provide support for "=" assignment operator?

For example:

S1 is object of class sample then we use like this: S2 = ++S1;

Overloading unary pre-increment operator

To implement operator overloading, we need to use "operator" keyword. To assign extra task to operator, we need to implement a function. That will provide facility to write expressions in most natural form.

C++ program to overload unary pre-increment operator

Consider the program:

using namespace std;
#include <iostream>

class Sample {
  // private data member
 private:
  int count;

 public:
  // default constructor
  Sample() { count = 0; }

  // parameterized constructor
  Sample(int c) { count = c; }

  // overloaded operator, returning an object
  Sample operator++() {
    Sample temp;
    temp.count = ++count;
    return temp;
  }

  // printing the value
  void printValue() { cout << "Value of count : " << count << endl; }
};

int main() {
  int i = 0;
  // objects declarations
  Sample S1(100), S2;

  for (i = 0; i < 5; i++) {
    // incrementing the object and assigning the value
    // in another object
    S2 = ++S1;
    // printing the value of S1 object
    cout << "S1 :" << endl;
    S1.printValue();
    // printing the value of S2 object
    cout << "S2 :" << endl;
    S2.printValue();
  }

  return 0;
}

Output

S1 :
Value of count : 101
S2 :
Value of count : 101
S1 :
Value of count : 102
S2 :
Value of count : 102
S1 :
Value of count : 103
S2 :
Value of count : 103
S1 :
Value of count : 104
S2 :
Value of count : 104
S1 :
Value of count : 105
S2 :
Value of count : 105

Explanation

In this program, we have created a class named Sample. It contains a data member value. And we have implemented a function to overload pre-increment operator with support of = (assignment operator).

We cannot use post-increment with this method of operator overloading.

We can use below statement also in place of S2 = ++S1: S2 = S1.operator++();

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.