Like Tree3Likes
  • 1 Post By whiteflags
  • 2 Post By phantomotap

Operator Overloading Help

This is a discussion on Operator Overloading Help within the C++ Programming forums, part of the General Programming Boards category; The program worked fine before implemeting operator overloading, demonstrated in objects #1-3. The goal is to add 4 overloaded operators ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    98

    Operator Overloading Help

    The program worked fine before implemeting operator overloading, demonstrated in objects #1-3.

    The goal is to add 4 overloaded operators as following:
    >>read new name and balance from keyboard and update the object's data
    << display the info for the object
    += increase balance
    -= decrease balance


    Now, when I run my program. Only the info for object 4 shows and it does not output a second time after adding 1000 to the total.

    Anything criticism and guidance is appreciated.

    Code:
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <conio.h>
    #include "SavingsAccount.h"
    using namespace std;
    ofstream fileout;
    int main()
    {
     fileout.open("E:\\SavingsOut.txt");      
     
     SavingsAccount Saver4 ("John", "Claude", 3250, 4);     
           
     cout << Saver4 << endl; 
     cin >> Saver4;
     Saver4 += 1000;
     cout << Saver4 << endl;
     // declare objects
     SavingsAccount Saver1 ("Margaret", "Olson", 2000, 1);
     SavingsAccount Saver2 ("Debra", "Baxter", 2);
     SavingsAccount Saver3 (3);
     
     Saver1.printData();
     Saver2.printData();
     Saver3.printData();
     
     // set new parameters for Saver2
     Saver2.setBalance (5000);
     
     // set new parameters for Saver3
     Saver3.setFirstName ("Arturo");
     Saver3.setLastName ("Ortiz");
     Saver3.setBalance (10000);
     
     // print new data for the objects
     cout<<"\nNew data for Saver 2:";
     fileout<<"\nNew data for Saver 2:";
     Saver2.printData();
     
     cout<<"\nNew data for Saver 3:";
     fileout<<"\nNew data for Saver 3:";
     Saver3.printData();
     cout<<"\nPress any key to continue.\n"<<endl;
     getch();
     
    }
    Code:
    #include "SavingsAccount.h"
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    using namespace std;
    extern ofstream fileout;
    double SavingsAccount::annualInterestRate = 0.00;
    // constructor function with 0 parameters
    SavingsAccount::SavingsAccount(int serial):objectnumber (serial)
    {
     setFirstName("");
     setLastName ("");
     setBalance (0.0);
     setInterestRate (.05);
     
    }
    // constructor functions with 1 parameter
    SavingsAccount::SavingsAccount (string first, string last, int serial ):objectnumber (serial)
    {
     setFirstName (first);
     setLastName (last);
     setBalance (0.0);
     setInterestRate (.05);
     
    }
    // constructor function with 2 parameters
    SavingsAccount::SavingsAccount(string first, string last, double balance, int serial):objectnumber (serial)
    {
     setFirstName (first);
     setLastName (last);
     setBalance (balance);
     setInterestRate (.05);
     
    }
    //destructor
    SavingsAccount::~SavingsAccount()
    {
     cout<< "Object " << objectnumber << " no longer exists" <<endl;
     fileout<< "Object " << objectnumber << " no longer exists" <<endl;
    }
    // calculate balance
    double SavingsAccount::calcNewBalance() 
    {
     monthlyRate = annualInterestRate/12;
     return (monthlyRate * savingBalance) + savingBalance;
    }
    
    void SavingsAccount::setInterestRate(double rate)
    {
     annualInterestRate = rate;
    }
    void SavingsAccount::setFirstName(string f)
    {
     firstName = f;
    }
    void SavingsAccount::setLastName(string l)
    {
     lastName = l;
    }
    // set balance
    void SavingsAccount::setBalance (double b)
    {
     savingBalance = b;
     
    }
    // get functions
    double SavingsAccount::getInterestRate()
    {
     return annualInterestRate;
    }
    int SavingsAccount::getObjectNumber () const
    {
     return objectnumber;
    }
    string SavingsAccount::getFirstName() 
    {
     return firstName;
    }
    string SavingsAccount::getLastName() 
    {
     return lastName;
    }
    // get balance
    double SavingsAccount::getBalance() const
    {
     return savingBalance;
    }
    //overloaded functions
    istream& operator>> (istream &cin, SavingsAccount &Saver4)
    {
     string f, l;
     double s;
     
     cin >> f >> l >> s;
     Saver4.firstName = f;
     Saver4.lastName = l;
     Saver4.savingBalance = s;
     return cin;
     
    }
    ostream& operator<< (ostream &out, SavingsAccount &Saver4)
    {
     cout << Saver4.getFirstName() << " " << Saver4.getLastName() << " " << Saver4.getBalance();
     return cout;
    }
    void SavingsAccount::operator += (double b)
    {
     savingBalance += b;
    }
    void SavingsAccount::operator -= (double b)
    {
     savingBalance -= b;
    }
    // print function
    void SavingsAccount::printData()
    {
     cout<< "\nSerial Number: " << objectnumber;
     cout<< "\nName: " << firstName <<" "<< lastName;
     cout<< "\nBalance: " << savingBalance;
     cout<< "\nNew Balalce: " << calcNewBalance()<<endl;
     fileout<< "\nSerial Number: " << objectnumber;
     fileout<< "\nName: " << firstName <<" "<< lastName;
     fileout<< "\nBalance: " << savingBalance;
     fileout<< "\nNew Balalce: " << calcNewBalance();
    }
    Code:
    #ifndef SAVINGSACCOUNT_H
    #define SAVINGSACCOUNT_H
    #include <string>
    using namespace std;
    class SavingsAccount
    {
    public:
     //overloaded constructor functions
     SavingsAccount (int);
     SavingsAccount (string, string, int);
     SavingsAccount (string, string, double, int);
     //destructor
     ~SavingsAccount();
     
     //set functions
     void setFirstName ( string );
     void setLastName ( string );
     void setBalance ( double );
     
     void static setInterestRate ( double );
     
     //get functions
     string getFirstName();
     string getLastName();
     double getBalance() const;
     int getObjectNumber () const;
     static double getInterestRate ();
     //calculation functions
     double calcNewBalance();
     //print functions
     void printData();
     //overloaded functions
     friend std::ostream& operator<< (ostream &, SavingsAccount&);
     friend std::istream& operator>> (istream &, SavingsAccount&); 
     void operator += (double);
     void operator -= (double);
    private:
     string firstName;
     string lastName;
     double savingBalance;
     double monthlyRate;
     static double annualInterestRate;
     const int objectnumber;
     
    };
    #endif

  2. #2
    Registered User
    Join Date
    Mar 2012
    Posts
    98
    Ah, I fixed the problem with none of the other object's running their task by declaring Saver4 after 3 and running through the task that way.

    Saver4 only shows "John Claude 3250" once and does not update the balance when I call Saver4 += 1000;

    Also, is there a way to allow the user to input John Claude 3250 from the keyboard and run it that way?

  3. #3
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    Well in general now that you are overloading operator >> and operator << you need to revision the member functions you used to use for this purpose. With output operators properly implemented, this is possible:

    Code:
    SavingsAccount saver ( /* properties */ );
    cout << saver << endl;
    file << saver << endl;
    Because when you define operator << you are supposed to use the ostream reference that gets passed in. C++ calls it like so:

    Code:
    cout.operator(cout, saver).operator(cout, endl);
    file.operator<<(file, saver).operator<<(file, endl);
    So what you need to ask yourself is if printData has any role in that call otherwise operator << effectively replaces it.

    Same thing with operator >> really. In a similar fashion that operator can be used to read in from any source and modify the object
    Last edited by whiteflags; 03-25-2013 at 06:29 PM.

  4. #4
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,255
    I fixed the problem with none of the other object's running their task by declaring Saver4 after 3 and running through the task that way.
    O_o

    I don't know what it is in your case, but in general, if the order of declaration changes the observable effects of a program that are unrelated to constructor you have something very wrong.

    By the by, would you be kind enough to tell us where you got this project example?

    C++ calls it like so
    O_o

    This would be closer:

    Code:
    operator << (operator << (cout, saver), endl);
    Soma

  5. #5
    Registered User
    Join Date
    Mar 2012
    Posts
    98
    Phantom,

    The project has been filled out by me. Although this site did help with the debugging along with my professor. He assigned for us to not change code we had previously but add in the overloaded operators.

    Can anyone see to as any reason as why my addition/subtraction operators do not work? Nor do the cout(s) after I call those functions.

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,596
    The << operator is wrong.
    Basically, a << b is you telling the compiler to take b and put it into the file a. But what does your function do? It puts it into cout instead of the "a" that is passed along to your function!
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    You need to take note of what I said. Your input and output operators are wrong -- you do not use all of the parameters which are passed in, which is bound to cause issues.

    If we take a look at the code:
    Code:
     fileout.open("E:\\SavingsOut.txt");     
      
     SavingsAccount Saver4 ("John", "Claude", 3250, 4);    
            
     cout << Saver4 << endl;
     cin >> Saver4;
     Saver4 += 1000;
     cout << Saver4 << endl;
    It can technically fail on lines before we get to add 1000. A quick run through the debugger confirms that we do not reach the line that you say is the problem.

  8. #8
    Registered User
    Join Date
    Mar 2012
    Posts
    98
    Whiteflags, I get what you're saying now it just took a minute to resonate. I actually have the arithmetic operators working correctly as well.

    As my code is currently constructed and how I declare my object in main, if I'm not mistaken I don't see any use for cin.

    How would I go about declaring a 4th object and then allowing the user to enter the name/balance for that object and then perform the given tasks upon them?

  9. #9
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    As my code is currently constructed and how I declare my object in main, if I'm not mistaken I don't see any use for cin.
    It will be used under the condition that you have to get input from the keyboard.

    How would I go about declaring a 4th object and then allowing the user to enter the name/balance for that object and then perform the given tasks upon them?
    These are separate tasks, actually. To answer the first part of the question, declare a default constructor for Savings Accounts. Then this is possible:
    Code:
    SavingsAccounts newAcct;
    cout << "Please enter your name followed by your initial deposit: ";
    cin >> newAcct;
    From there manipulating the account happens as normal.

  10. #10
    Registered User
    Join Date
    Mar 2012
    Posts
    98
    Updated calls

    Code:
    operator << (cout, Saver4);
    
    Saver4 += 1000;
    operator << (cout, Saver4);
    
    Saver4 -= 1000;
    operator << (cout, Saver4);

  11. #11
    Registered User
    Join Date
    Mar 2012
    Posts
    98
    Wow that simple, I over complicated things in my head I guess.

    I went ahead and used my construtor that declares a serial number only for the user and then asked for the info. But thanks all for clearing up my confusions with overloading.

  12. #12
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,699
    O_o

    Code:
    ostream& operator<< (ostream &out, SavingsAccount &Saver4)
    {
     cout << Saver4.getFirstName() << " " << Saver4.getLastName() << " " << Saver4.getBalance();
     return cout;
    }
    cout is just one ostream of many. out actually refers to any of them, in particular, the one being used at the moment, whether it is cout, or another file or perhaps even a network stream, or...

    And:
    Code:
    //overloaded functions
    istream& operator>> (istream &cin, SavingsAccount &Saver4)
    {
     string f, l;
     double s;
      
     cin >> f >> l >> s;
     Saver4.firstName = f;
     Saver4.lastName = l;
     Saver4.savingBalance = s;
     return cin;
     }
    cin is one example of a whole class.

    The example I wrote which you reproduced was meant for your understanding. I wanted to communicate that when you called the operator function, the parameters would be filled with arguments, in fact dictating where the ultimate results go (or come from, as in the case of input). It is not necessary to change how these statements are written. This is my fault for not explaining this properly.
    laserlight likes this.

  13. #13
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,255
    O_o
    *gasp*

    THAT'S MY LINE!

    Soma
    Matticus and laserlight like this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. operator overloading
    By dontoo in forum C++ Programming
    Replies: 3
    Last Post: 02-19-2010, 06:26 AM
  2. C++ operator overloading
    By mubashariqbal in forum C++ Programming
    Replies: 19
    Last Post: 07-13-2006, 06:19 AM
  3. overloading >> operator
    By Diamonds in forum C++ Programming
    Replies: 1
    Last Post: 03-21-2003, 01:01 AM
  4. operator overloading
    By tsut in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2002, 08:26 AM
  5. operator overloading
    By Kohatian 3279 in forum C++ Programming
    Replies: 1
    Last Post: 03-28-2002, 08:00 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21