×

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

How to overload post-decrement operator using non-member or free function in C++?

Post-decrement operator overloading in C++: Using C++ program, here we will learn how to overload post-decrement operator using non-member or free function?

Prerequisite: operator overloading and its rules

Here, we are going to implement a C++ program that will demonstrate operator overloading (post-decrement) using non-member or free member function.

Note: This type of non-member function will access the private member of class. So the function must be friend type (friend function).

C++ program to overload post-decrement operator using non-member or free function

Consider the program:

using namespace std;
#include <iostream>

// Sample class to demonstrate operator overloading
class Sample {
  // private data members
 private:
  int value;

 public:
  // Parameterized constructor
  Sample(int c) { value = c; }

  // making operator overloading declaration as
  // friend function
  friend Sample operator--(Sample &S, int);

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

// overator overloading function definition
Sample operator--(Sample &S, int) {
  S.value--;
  return S;
}

// main program
int main() {
  int i = 0;
  // object declaration
  // with parameterized constructor calling
  Sample S1(100);

  for (i = 0; i < 5; i++) {
    S1--;
    S1.printValue();
  }

  return 0;
}

Output

Value is : 99
Value is : 98
Value is : 97
Value is : 96
Value is : 95

Comments and Discussions!

Load comments ↻





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