C++/Operator Overloading
Expert: Eddie - 1/29/2008
QuestionHello Sir,How r u?,hope that u will be fine.Sir i have few questions:
1.First i want to know what is meant by catastrophic failure due to array over run?
2.My second question is about operator overloading.What is Operator Overloading,why it is required and how it is done?
thanks Good Day Sir.
AnswerHello Irshad, thank you for the question.
To answer your first question, this means you are accessing an array outside of the memory allocated for it. Here is a very simple example:
int array[3] = {0, 1, 2};
cout << array[100];
There you have allocated an array with 3 items, and then try to access the 100th item in the array, which is the error you describe.
To answer your second question, operator overloading is a way to customize an operator on a class. This can become extremely handy in certain situations. Here is a simple example where we will overload the + and << operators:
class Vector
{
Vector()
{
x = y = z = 0;
}
Vector & operator + (const Vector &other)
{
this->x += other.x;
this->y += other.y;
this->z += other.z;
return *this;
}
std::ostream& operator << (const std::ostream &o)
{
o << "Vector values are: " << x << ' ' << y << ' ' << 'z';
return o;
}
private:
int x, y, z;
}
Now, in code we can use the overloaded + and << operators to add 2 vectors, and to cout a vector, respectively:
// in main
Vector one, two;
std::cout << one << std::endl << two << std::endl;
Vector three = one + two;
The compiler by default does not know how to print or add non-primitive typed objects, so we can use operator overloading to customize.
I hope this information was helpful.
- Eddie