Demonstrate prefix and postfix ++ : overload unary operator « Operator Overloading « C++ Tutorial






#include <iostream> 
using namespace std; 
 
class ThreeD { 
  int x, y, z; 
public: 
  ThreeD() { x = y = z = 0; } 
  ThreeD(int i, int j, int k) {x = i; y = j; z = k; } 
 
  ThreeD operator++(); // prefix version of ++ 
  ThreeD operator++(int notused); // postfix version of ++ 
 
  void show() ; 
}; 
 
// Overload the prefix version of ++. 
ThreeD ThreeD::operator++() 
{ 
  x++;  // increment x, y, and z 
  y++; 
  z++; 
  return *this; // return altered value 
} 
 
// Overload the postfix version of ++. 
ThreeD ThreeD::operator++(int notused) 
{ 
  ThreeD temp = *this; // save original value 
 
  x++; // increment x, y, and z 
  y++; 
  z++; 
  return temp; // return original value 
} 
 
// Show X, Y, Z coordinates. 
void ThreeD::show( ) 
{ 
  cout << x << ", "; 
  cout << y << ", "; 
  cout << z << "\n"; 
} 
 
int main() 
{ 
  ThreeD a(1, 2, 3); 
  ThreeD b; 
 
  cout << "Original value of a: "; 
  a.show(); 
 
  ++a; // prefix increment 
  cout << "Value after ++a: "; 
  a.show(); 
 
  a++; // postfix increment 
  cout << "Value after a++: "; 
  a.show(); 
 

  b = ++a; 
  cout << "\nValue of a after b = ++a: "; 
  a.show(); 
  cout << "Value of b after b = ++a: "; 
  b.show(); 
 
  b = a++; 
  cout << "\nValue of a after b = a++: "; 
  a.show(); 
  cout << "Value of b after b = a++: "; 
  b.show(); 
 
  return 0; 
}
Original value of a: 1, 2, 3
Value after ++a: 2, 3, 4
Value after a++: 3, 4, 5

Value of a after b = ++a: 4, 5, 6
Value of b after b = ++a: 4, 5, 6

Value of a after b = a++: 5, 6, 7
Value of b after b = a++: 4, 5, 6








10.8.overload unary operator
10.8.1.Overloading ++
10.8.2.Overloading the increment operator
10.8.3.Overload the ++ unary operator
10.8.4.Overload the postfix version of ++.
10.8.5.Demonstrate prefix and postfix ++
10.8.6.Overload prefix ++ for Point
10.8.7.Lvalues and rvalues
10.8.8.Using a Friend to Overload ++ or – –