I am stuck trying to figure out the +operator overload. My =operator works just fine. I am a newb to this forum and just learning c++ I have tried to make my sample match what the book shows with my own variables but it doesn't appear to be working correctly. Any help would be appreciated.
Thanks in advance.
Source code
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
class Item
{
private:
int value;
double size;
double cost;
char *description;
char *name;
public:
Item() // Constructor - initializes variables to 0 or null
{
value = 0;
size = 0.0;
cost = 0.0;
description = NULL;
name = NULL;
}
Item(int v, double s, double c, char*d, char*n) // Constructor allowing arguments to set values
{
value = v;
size = s;
cost = c;
description = new char[strlen(d)+1];
strcpy(description, d);
name = new char[strlen(n) + 1];
strcpy(name, n);
}
Item(const Item &obj) // Copy Constructor
{
value = obj.value;
size = obj.size;
cost = obj.cost;
description = new char[strlen(obj.description) + 1];
strcpy(description, obj.description);
name = new char[strlen(obj.name) + 1];
strcpy(name, obj.name);
}
~Item()// destructor
{
}
void setValue(int v)
{value = v;}
void setSize(double s)
{size = s;}
void setCost(double c)
{cost = c;}
void setDescription(char *d)
{description = d;}
void setName(char *n)
{name = n;}
int getValue()
{return value;}
double getSize()
{return size;}
double getCost()
{return cost;}
char *getDescription()
{return description;}
char *getName()
{return name;}
void operator=(const Item &right)
{
value = right.value;
size = right.size;
cost = right.cost;
delete [] description;
description = new char[strlen(right.description) + 1];
strcpy(description, right.description);
delete [] name;
name = new char[strlen(right.name) + 1];
strcpy(name, right.name);
}
Item operator + (const Item &);
bool operator == (const Item &);
};
Item Item::operator + (const Item &right)
{
Item temp;
temp.value = value + right.value;
temp.size = right.size;
temp.cost = right.cost;
temp.description = right.description;
temp.name= right.name;
strcpy(temp.description, right.description);
strcpy(temp.name, right.name);
return temp;
}
int main()
{
Item first (10, 16.0, 8.95, "bottle1", "liquid gold1");
Item second (11, 17.0, 9.95, "bottle2", "liquid gold2");
Item third; //(12, 18.0, 10.95, "bottle3", "liquid gold3");
//****************************************************
//Here is the area that I am having trouble with
//The program compiles and runs but the +operator doesnt
//do anything. It only returns the value of third without
//performing the first + second
Item widget3 = widget1;
third = first + second;
cout << "First = " << first.getValue() << endl;
cout << "Second = " << second.getValue() << endl;
cout << "first + second = " << third.getValue() << endl;
//*****************************************************
//*****************************************************
}
Edited by NaGaSaKi71, 17 June 2005 - 12:31 PM.