Hi,
Let's say you have a simple class defined like this:
Code:
class Box
{
public:
Box(string str, int n) //constructor
{
type = str;
items = n;
}
Box() //default constructor
{
type = "";
items = 0;
}
void show() //displays member variables
{
cout<<"Box type: "<<type<<endl
<<"Box items: "<<items<<endl;
}
private:
string type;
int items;
};
Now suppose you want to add two boxes together. If you write:
Code:
int main()
{
Box A("candy", 3);
Box B("popcorn", 5);
Box C;
C = A + B;
return 0;
}
You will get an error because the compiler doesn't know what you mean when you say you want to add two Box objects together. What should the result be? When you create objects of your classes, you have to tell the compiler what result you want when you add two of your objects together. So you need to "overload" the operator+() in order to tell the compiler what the result should be. Each operator overload you write requires a unique format, so you need some resource for looking up the correct format. Pay particular attention to the parameter types and the return type. Here is the format for overloading operator+():
Code:
#include <iostream>
#include <string>
using namespace std;
class Box
{
public:
Box(string str, int n)
{
type = str;
items = n;
}
Box()
{
type = "";
items = 0;
}
void show()
{
cout<<"Box type: "<<type<<endl
<<item count: "<<items<<endl;
}
Box operator+(const Box& rhs) const
{
Box combined;
combined.type = "combined items";
combined.items = this->items + rhs.items;
return combined;
}
private:
string type;
int items;
};
int main ()
{
Box A("candy", 3);
Box B("popcorn", 5);
Box C = A + B;
C.show(); //Box type: combined items
//item count: 8
return 0;
}
You should note that the line:
calls the default assignment operator: operator=(). The compiler provides a default assignment operator for your classes, and the default assignment operator makes a member by member copy of what's on the right hand side(rhs) into the members of the object on the left hand side(lhs). If that is not the behavior you want, then you have to overload the operator=() for your class. You will usually overload operator=() if your objects have members that are pointers to dynamically created memory. In that case, you can overload operator=() to prevent two objects from pointing to the same dynamically created memory, which would cause a change in one object to affect the other object.