Monday 6 April 2015

Subscript Operator Overloading

The subscript operator [ ] can be overloaded to access the attributes of an object. It is mainly useful for bounds checking while accessing elements of an array.

For example the statement int a[10];

Where 10 indicates the number of locations, where we cannot give the value either by float or char. Because the locations must be integer. We can break this concept by using the subscript operator overloading.

Sample Program

#include <iostream.h>
class sub
{
public:
void operator[](char *n)
{
cout<<”Subscript operator with string”<<endl;
cout<<”Given string is “<<n<<endl;
}
void operator[](float fl)
{
cout<<”Subscript operator with float”<<endl;
cout<<”Given float value is “<<fl<<endl;
}
void operator[](char n)
{
cout<<”Subscript operator with character”<<endl;
cout<<”Given character is “<<n<<endl;
}
};
void main()
{
A[“Subscript”];
A[123.34];
A[‘c’];
}

No comments:

Post a Comment