Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overloading operators

Status
Not open for further replies.

H3RO

Programmer
Jan 8, 2003
12
0
0
LT
Hi all. I'm learning classes now and it seems ok to me , but the heck I just can't understand the thing named Overloading....It's so confusing to me and think there's no way I could understand without you. I would be very appriciative if you could help me through with the easyest examples for me to understand it in english, i want to learn it so badly.

Why to overload? How? Where?

btw, could someone give me a code example of how to oveload these operators: multiplication , == , !=
 
>> Why to overload?

If you want your class to behave like a certain abstract type, for example if you have a class called Complex, you might want to overload +, -, *, etc. to implement complex number arithmetic.

>> How? Where?
Overloading operators is just like adding member functions to your class. You put a prototype for the operator in your class definition, then you implement the operator in a CPP file.

>> could someone give me a code example of how to oveload these operators
No. That is such a general question I can't help you. Could someone give me a code example of how to write a Windows program?

Chapter 11 of Stroustrup's The C++ Programming Language (2nd ed.) goes into great detail on operators.
 
Why the overload? Because you have to implement a way to specify how the actions executed by the operators will affect your objects.

OK, let's say that you have created a class named MyClass. Somewhere in your program you have 2 objects from MyClass, let's call them obj1 and obj2.

MyClass obj1;
...
MyClass obj2;

Now, say you need to compare the 2 objects and take an action based on the result:

if (obj1==obj2)
do_this;
else
do_that;

The compiler doesn't know how to compare the 2 objects. You have to tell the compiler which members of the class it should test.

Let's say that MyClass looks like this

class MyClass
{
public:
MyClass() {}
~MyClass() {}
int Anumber;
BOOLEAN operator == (const MyClass & temp);
};

BOOLEAN MyClass::eek:perator == (const MyClass & temp)
{
if (Anumber==temp.Anumber) return TRUE;
return FALSE;
}

In this example, two objects from MyClass are equal if their member variables Anumber are equal.


Hope this helps
Radu
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top