You are here:

C++/Operator Overloading

Advertisement


Question
Hello 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.

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.