Thursday 26 February 2015

Operator Overloading in C++ : PART 2 ([ ] Operator)



  Array subscript operator [ ] used for array indexing can also be overloaded in C++. In this post I have added a program in which the array subscript operator [ ] is overloaded. The program illustrates an overloaded array subscript operator.

The program also offers a solution to the C++ puzzle question given below.

Floating Point Number in Array Subscript

Write a C++ program in which the following statement compiles without an error.

cout << a[0.123];

The difficulty in solving this puzzle arises from the fact that array subscript should be an integer.  

If you pass a float value to a normal array subscript you will get the following error "Invalid type for array subscript". 

One possible solution is to overload the array subscript operator.


There might be some other solutions to this puzzle. If you know any other solution please share them here. 
   

Wednesday 25 February 2015

Operator Overloading in C++ : PART 1 (++ Operator)



 I am now teaching under graduate students C++ programming. I thought I will share the programs I have prepared so that it benefits everyone.

Overloading ++ Operator

In this post I have added sample programs overloading the ++ Operator. In C++ we have preincrement and postincrement operators. For example ++a is preincrement whereas a++ is postincrement. So in order to handle these two situations there should be two versions of the operator++( ) function. The two versions are shown below. 

    void operator++(int y);  // for postincrement
   // The call a++; will invoke this version
   // The call a++; is same as the call a.operator++();
   
   void operator++( );        // for preincrement
   // The call ++a; will invoke this version
   // The call ++a; is same as the call a.operator++(0);


Click here to download the C++ program. 


Overloading ++ Operator with Friend Function
In C++ we can overload the ++ operator by using friend function.  Here also we need two versions to manage the preincrement and postincrement versions of the ++ operator. The two versions are given below.

   void operator++(A, int);  // for postincrement
   // The name of the Class is A
   // The call a++; will invoke this version
   // The call a++; is same as the call operator++(a);
   
   void operator++(A);        // for preincrement
   //The name of the class is A 
   // The call ++a; will invoke this version
   // The call ++a; is same as the call operator++(a,0);

Click here to download the C++ program.