Solved

Operator overload +

Posted on 2004-03-26
8
309 Views
Last Modified: 2008-02-26
can someone please help me on operator overloading +
I have supplied the main file and the implementation file.  I am writing an application that records the items (books) sold and calculates/displays the totals (costprice and sellprice) and the average total sales for each day.  i'm not getting the results i'm expecting.  The problem is in the operator overload :
The out-put should be something like this:

report for monday, march 02, 2004
  Total Sales: $180
   Total Cost: $150
   Average: $15.00
report for tues...etc.,
In my main class i record the sales like this and then call the copy constructor:

StockItem text1("W. Savitch", "Absolute C++ 1/e",
"Addison/Wesley", "2002", 75, 90);
    StockItem text2("L. A. Robertson", "Simple Program Design 4/e",
"Thomson", "2003", 70, 80);
    StockItem text3("A. Silberschatz, P. B. Galvin, and G. Gagne",
"Operating System Concepts 6/e", "John Wiley & Sons", "2003", 85, 120);

    SalesRegister monday("Monday March 1, 2004", 0, 0, 0);
    cout << monday.getDescription() << endl;
    monday.RecordSale(text1);
    monday.RecordSale(text1);

// COPY CONSTRUCTOR
    SalesRegister::SalesRegister(const SalesRegister& regObject)
    :Description(regObject.getDescription()),TotalCostPrice(regObject.getTotalCostPrice()),
    TotalSellPrice(regObject.getTotalSellPrice()),
        ItemCount(regObject.getItemCount())
   {
   }
// Calling the copy constrcutor
SalesRegister total(monday + tuesday + wednesday + thursday + friday);

#include<iostream>
#include<iomanip>
#include<string>

   using namespace std;
   using std::ios;

#include "SalesRegister.h"
#include "StockItem.h"

// USER DEFINED CONSTRUCTOR
    SalesRegister::SalesRegister(string Description, int TotalCostPrice,int
    TotalSellPrice, int ItemCount)
   {
      this->setDescription(Description);
      this->setTotalCostPrice(TotalCostPrice);
      this->setTotalSellPrice(TotalSellPrice);
      this->setItemCount(ItemCount);
   
   // INITIALISE PRIVATE MEMBERS TO DEFAULT VALUES
      Description = "";
      TotalCostPrice = 0;
      TotalSellPrice = 0;
      ItemCount = 0;
   }

// COPY CONSTRUCTOR
    SalesRegister::SalesRegister(const SalesRegister& regObject)
    :Description(regObject.getDescription()),TotalCostPrice(regObject.getTotalCostPrice()),
    TotalSellPrice(regObject.getTotalSellPrice()),
        ItemCount(regObject.getItemCount())
   {
   }

// OPERATOR OVERLOADING  + ADDITION
    SalesRegister SalesRegister::operator+(const SalesRegister &temp)
   {
      SalesRegister tmp(*this);
   // PROBLEM HERE
      TotalCostPrice = TotalCostPrice + temp.TotalCostPrice;
      TotalSellPrice = TotalSellPrice + temp.TotalSellPrice;
      temp.ItemCount + 1; // item count for average
   
      return(tmp);
   
   }
// ACCESSOR & MUTATOR FUNCTIONS

    string SalesRegister::getDescription() const
   {
      return(this->Description);
   }

    int SalesRegister::getTotalCostPrice() const
   {
      return(this->TotalCostPrice);
   }

    int SalesRegister::getTotalSellPrice() const
   {
      return(this->TotalSellPrice);
   }

    int SalesRegister::getItemCount() const
   {
      return(this->ItemCount);
   }

    string SalesRegister::setDescription(string Description)
   {
      return(this->Description = Description);
   }

    int SalesRegister::setTotalCostPrice(int TotalCostPrice)
   {
      return(this->TotalCostPrice = TotalCostPrice);
   }

    int SalesRegister::setTotalSellPrice(int TotalSellPrice)
   {
      return(this->TotalSellPrice = TotalSellPrice);
   }

    int SalesRegister::setItemCount(int ItemCount)
   {
      return(this->ItemCount = ItemCount);
   }

    void SalesRegister::RecordSale(StockItem Item)
   {
   
      cout << "\t" << Item.getSellPrice() << "\t" << Item.getAuthor() << ", "
         << Item.getPublisher() << ", " << Item.getYear() << endl;
   
      TotalCostPrice = Item.getCostPrice();
      TotalSellPrice = Item.getSellPrice();
   
   }

// PRINT THE REPORT
    void SalesRegister::PrintReport()
   {
      cout << endl;
      cout << "Report for " << getDescription() << endl;
      cout << "\t" << "Total Sales: " << "\t$" << getTotalSellPrice() << endl;
      cout << "\t" << "Total Cost: " << "\t$" << getTotalCostPrice() << endl;
   
      float i = TotalSellPrice - TotalCostPrice;
   
      cout.setf(ios::fixed);
      cout.setf(ios::showpoint);
   // Avergage & ItemCount under construction
   //cout << "\t" << "Average Profit: " << "$" << setprecision(2) << i << endl;
   }

// DESTRUCTOR
    SalesRegister::~SalesRegister()
   {
   }


#include <iostream>
#include <string>

using namespace std;

#include "SalesRegister.h"
#include "StockItem.h"

int main()
{
    StockItem text1("W. Savitch", "Absolute C++ 1/e",
"Addison/Wesley", "2002", 75, 90);
    StockItem text2("L. A. Robertson", "Simple Program Design 4/e",
"Thomson", "2003", 70, 80);
    StockItem text3("A. Silberschatz, P. B. Galvin, and G. Gagne",
"Operating System Concepts 6/e", "John Wiley & Sons", "2003", 85, 120);

    SalesRegister monday("Monday March 1, 2004", 0, 0, 0);
    cout << monday.getDescription() << endl;
    monday.RecordSale(text1);
    monday.RecordSale(text1);

    SalesRegister tuesday("Tuesday March 2, 2004", 0, 0, 0);
    cout << endl << tuesday.getDescription() << endl;
    tuesday.RecordSale(text3);
    tuesday.RecordSale(text2);
    tuesday.RecordSale(text1);

    SalesRegister wednesday("Wednesday March 3, 2004", 0, 0, 0);
    cout << endl << wednesday.getDescription() << endl;
    wednesday.RecordSale(text1);
    wednesday.RecordSale(text3);

    SalesRegister thursday("Thursday March 4, 2004", 0, 0, 0);
    cout << endl << thursday.getDescription() << endl;
    thursday.RecordSale(text3);
    thursday.RecordSale(text2);

    SalesRegister friday("Friday March 5, 2004", 0, 0, 0);
    cout << endl << friday.getDescription() << endl;
    friday.RecordSale(text1);
    friday.RecordSale(text2);

    SalesRegister total(monday + tuesday + wednesday + thursday + friday);
    total.setDescription("Total Sales");

    monday.PrintReport();
    tuesday.PrintReport();
    wednesday.PrintReport();
    thursday.PrintReport();
    friday.PrintReport();
    total.PrintReport();

    return(0);
}


0
Comment
Question by:gbilios
  • 3
  • 3
  • 2
8 Comments
 
LVL 9

Accepted Solution

by:
_ys_ earned 20 total points
ID: 10693883
Your operator + overload never changes 'tmp' - the final instance you return. It does in fact alter 'this'.

SalesRegister SalesRegister::operator+(const SalesRegister &temp)
{
    SalesRegister tmp(*this);
   // PROBLEM HERE
    tmp.TotalCostPrice += temp.TotalCostPrice;
    tmp.TotalSellPrice += temp.TotalSellPrice;

// not sure about this ??
    temp.ItemCount + 1; // item count for average

// did you mean ...
    tmp.ItemCount += temp.ItemCount;
   
    return(tmp);
}

You'll realise that everything is just tmp += temp. As such the canonical format of an implementation is:

const SalesRegister SalesRegister::operator+(const SalesRegister &temp)
{
    SalesRegister tmp(*this);
    tmp += temp;
    return(tmp);
}

Reusing operator+= avoids any unexpected results, and ensures consistency among your operators' custom implemtations.
0
 

Author Comment

by:gbilios
ID: 10694143
Thanks for your help.  i worked out the problem.  The one thing remaining is the total sales and cost for the whole week.  

In my main application i call the copy constructor:

SalesRegister total(monday + tuesday + wednesday + thursday + friday);

below is the copy constructor:

// COPY CONSTRUCTOR
    SalesRegister::SalesRegister(const SalesRegister& regObject)
    :Description(regObject.getDescription()),TotalCostPrice(regObject.getTotalCostPrice()),
    TotalSellPrice(regObject.getTotalSellPrice()),
        ItemCount(regObject.getItemCount())
   {


     
   }


0
 
LVL 9

Expert Comment

by:_ys_
ID: 10694250
The copy constructor looks sound, and is already being used from within operator+.

You'll need to verify the output from operator+. I believe that's the source of your problem. Perform a simple monday + tuesday and verify the results.
0
 

Author Comment

by:gbilios
ID: 10694287
I'm new to programming so it'll take me a while to get everything working in order.
I can't have the code:
tmp += temp;  //I GET A COMPILE ERROR

Do i need to include anything else in the copy constructor?
i modified the code to:

SalesRegister SalesRegister::operator+(const SalesRegister &temp)
{
   SalesRegister tmp(*this);

    tmp.TotalCostPrice + temp.TotalCostPrice;
   tmp.TotalSellPrice + temp.TotalSellPrice;
    tmp.ItemCount + temp.ItemCount;
return(tmp);
}

void RecordSale(StockItem Item)
{
  TotalCostPrice = TotalCostPrice + Item.getCostPrice();
  TotalSellPrice = TotalSellPrice + Item.getSellPrice();
ItemCount++;
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:gbilios
ID: 10694306
no wonder it aint working, stupid me!!

the code in the operator should've read:

tmp.TotalSellPrice = tmp.TotalSellPrice + temp.TotalSellPrice;
tmp.TotalCostPrice = tmp.TotalCostPrice + temp.TotalCostPrice;

//What was happening when the call to the constructor in the main class:
SalesRegister total(monday + tuesday + wednesday + thursday + friday);

would only get the first instance of the totalcost/totalsell price for monday

everythings okay!!
THANK-YOU!!
0
 
LVL 9

Expert Comment

by:_ys_
ID: 10702747
>> tmp += temp;
This requires you to overload operator+= with your own implementation. Not absolutely necessary, just good pratice.
0
 
LVL 20

Expert Comment

by:Venabili
ID: 10732394
gbilios,

Can you please accept the answer of the expert that helped you? Thanks

Venabili
Programming Languages Page Editor
0
 
LVL 20

Expert Comment

by:Venabili
ID: 10732566
Why did you accepted my answer? I will reopen and accept the answer of the expert

Venabili
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now