vector virtualViaPointer -- Need help - one question

This is a discussion on vector virtualViaPointer -- Need help - one question within the C++ Programming forums, part of the General Programming Boards category; Hello Everyone, I'm getting close. This code was compile using Dev-5-cpp and it will compile and run under VS-2008. I ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    90

    vector virtualViaPointer -- Need help - one question

    Hello Everyone,

    I'm getting close. This code was compile using Dev-5-cpp and it will compile and run under VS-2008. I spend a lot of time piecing this code together and I have a lot of extra work to do in order to finish up.

    I only have "one question" but it may take a minute to understand what I'm asking. Compile the program and go to this lines (use/copy paste/find). It's in two places and it's the ONLY question.


    // I need an Extra virtual call to ***getBalance*** from the
    // CHECKING_A::CHECKING_A. I need it to replace the call
    // **checking_A.earnings()** below, which only return interest
    // earned. I need the Balance which is $25.00 using virtual
    // base-class reference or pointer. Thanks in advance


    Thank you


    Code:
    // Processing derived-class obj ieach and poly using dynamic binding.
    
    #include <stdio.h>
    #include <iostream>
    #include <iomanip>
    #include <string.h>
    #include <time.h>
    #include <ctime>
    #include <sstream>
    #include <string>
    #include <Cstring>
    #include<stdlib.h>
    #include <iostream>
    #include <iomanip>
    #include <limits>           // numeric_limits needed by VC
    #include <vector>
    
    using namespace std;        // for iostream
    using std::cout;
    using std::cin;
    using std::endl;
    using std::vector;
    
    
    using std::setprecision;    // for iomanip
    using std::fixed;
    
    // ............................................     cannot instantiate objects
    // ............................................     ACCOUNT abstract base class
    // ..................   pure virtual function makes ACCOUNT abstract base class
    class ACCOUNT 
    {
    public:
       ACCOUNT( const string & );
    
       void set_ID( const string & );
       string get_ID() const;
    
    
               void    credit     ( double );
               bool    debit      ( double );
               void    setBalance ( double );
               double  getBalance();
     
       virtual double earnings() const = 0;                   // pure virtual
       virtual void print() const;                            // virtual
    private:
            double  balance;        
            string line_ID;
    };
    // ............................................ concrete with intent to override
    // ............................................             derived from ACCOUNT
    class SAVING_A : public ACCOUNT 
    {
    public:
       SAVING_A( const string &, double = 0.0, double = 0.0 );
    
       void setInterestRate( double );
       double getInterestRate() const;
    
       void setBalance( double );
       double getBalance() const;
    
       virtual double earnings() const;
       virtual void print() const;
    private:
       double balance;
       double interestRate;
    };
    // ............................................ concrete with intent to override
    // ............................................             derived from ACCOUNT
    class saving_B : public ACCOUNT 
    {
    public:
       saving_B( const string &, double = 0.0, double = 0.0 );
    
       void setInterestRate( double );
       double getInterestRate() const;
    
       void setBalance( double );
       double getBalance() const;
    
       virtual double earnings() const;
       virtual void print() const;
    private:
       double balance;
       double interestRate;
    };
    // ............................................ concrete with intent to override
    // ............................................             derived from ACCOUNT
    class CHECKING_A : public ACCOUNT 
    {
    public:
       CHECKING_A( const string &, double = 0.0, double = 0.0 );
    
       void setInterestRate( double );
       double getInterestRate() const;
    
       void setBalance( double );
       double getBalance() const;
    
       virtual double earnings() const;
       virtual void print() const;
    private:
       double balance;
       double interestRate;
    };
    // ............................................   derive from CommissionACCOUNT
    // ..............................     keyword virtual signals intent to override
    class checking_B : public CHECKING_A 
    {
    public:
       checking_B( const string &,
                                     double = 0.0, double = 0.0, double = 0.0 );
       void setCompoundInterest( double );
       double getCompoundInterest() const;
    
       virtual double earnings() const;                       //  intent 22 override
       virtual void print() const;                            //  intent 22 override
    private:
       double compoundInterest;
    };
    
    // Process ACC derived-class objects individually & poly using dynamic binding
    //----------------------------------------------------------       constructor
    ACCOUNT::ACCOUNT( const string &_id_0 )
       : line_ID( _id_0 )
    {
    }
    //----------------------------------------------------------              _id_0
    void ACCOUNT::set_ID( const string &_id_0 )
    {   line_ID = _id_0;  }
    
    string ACCOUNT::get_ID() const
    {   return line_ID;   }
    //---------------------------------------------------------   not pure virtual
    void ACCOUNT::print() const            //  
    { 
       cout << "\n" << get_ID(); 
    }
    
    
    
    
    
    
    
    // Process ACC derived-class objects individually & poly using dynamic binding
    //----------------------------------------------------------      constructor
    SAVING_A::SAVING_A(const string &_id_0, double initialBalance, double rate)
       : ACCOUNT( _id_0 )  
    {    setBalance( initialBalance );
         setInterestRate( rate );  }
    //----------------------------------------------------------        InterestRate
    void   SAVING_A::setInterestRate( double rate )
    {      interestRate = ( ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0 ); }
    double SAVING_A::getInterestRate() const
    {      return interestRate;  }
    //----------------------------------------------------------             Balance
    void SAVING_A::setBalance( double initialBalance ) 
    {    balance = ( ( initialBalance < 0.0 ) ? 0.0 : initialBalance );  }
    double SAVING_A::getBalance() const
    {    return balance;  }
    //--------------------------------------------- override pure virtual in ACCOUNT
    double SAVING_A::earnings() const
    {    return getInterestRate() * getBalance();  }
    //-----------------------------------------------    reuse E abstract base-class
    void SAVING_A::print() const
    {  cout << "SAVING_A: ";
       ACCOUNT::print();
       cout << "\nBalance: " << getBalance() 
          << "; iRate: " << getInterestRate();  }
    
    
    
    // Process ACC derived-class objects individually & poly using dynamic binding
    //----------------------------------------------------------        constructor
    saving_B::saving_B(const string &_id_0, double initialBalance, double rate)
       : ACCOUNT( _id_0 )  
    {    setBalance( initialBalance );
         setInterestRate( rate );  }
    //----------------------------------------------------------        InterestRate
    void   saving_B::setInterestRate( double rate )
    {      interestRate = ( ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0 ); }
    double saving_B::getInterestRate() const
    {      return interestRate;  }
    //----------------------------------------------------------             Balance
    void saving_B::setBalance( double initialBalance ) 
    {    balance = ( ( initialBalance < 0.0 ) ? 0.0 : initialBalance );  }
    double saving_B::getBalance() const
    {    return balance;  }
    //--------------------------------------------- override pure virtual in ACCOUNT
    double saving_B::earnings() const
    {    return getInterestRate() * getBalance();  }
    //-----------------------------------------------    reuse E abstract base-class
    void saving_B::print() const
    {  cout << "saving_B: ";
       ACCOUNT::print();
       cout << "\nBalance: " << getBalance() 
          << "; iRate: " << getInterestRate();  }
    
    
    
    
    //----------------------------------------------------------        constructor
    CHECKING_A::CHECKING_A(const string &_id_0, double initialBalance, double rate)
       : ACCOUNT( _id_0 )  
    {    setBalance( initialBalance );
         setInterestRate( rate );  }
    //----------------------------------------------------------        InterestRate
    void   CHECKING_A::setInterestRate( double rate )
    {      interestRate = ( ( rate > 0.0 && rate < 1.0 ) ? rate : 0.0 ); }
    double CHECKING_A::getInterestRate() const
    {      return interestRate;  }
    //----------------------------------------------------------             Balance
    void CHECKING_A::setBalance( double initialBalance ) 
    {    balance = ( ( initialBalance < 0.0 ) ? 0.0 : initialBalance );  }
    double CHECKING_A::getBalance() const
    {    return balance;  }
    //--------------------------------------------- override pure virtual in ACCOUNT
    double CHECKING_A::earnings() const
    {    return getInterestRate() * getBalance();  }
    //-----------------------------------------------    reuse E abstract base-class
    void CHECKING_A::print() const
    {  cout << "CHECKING_A: ";
       ACCOUNT::print();
       cout << "\nBalance: " << getBalance() 
          << "; iRate: " << getInterestRate();  }
    
    
    
    
    
    
    
    
    
    //----------------------------------------------------------        constructor
     checking_B::checking_B( const string &_id_0, double initialBalance,
                                                      double rate, double BALANCE )
     : CHECKING_A( _id_0, initialBalance, rate )  
     { setCompoundInterest( BALANCE );  }
    //----------------------------------------------------------   CompoundInterest
     void checking_B::setCompoundInterest( double BALANCE )
     {    compoundInterest = ( ( BALANCE < 0.0 ) ? 0.0 : BALANCE );  }
    
     double checking_B::getCompoundInterest() const
     {    return compoundInterest;  }
    //----------------------------------------------- override irtual in CHECKING_A
     double checking_B::earnings() const
     {    return getBalance() + CHECKING_A::earnings();  }
    
    //-----------------------------------------------    reuse C abstract base-class
     void checking_B::print() const
     {                                              // cout checking_B is OVER-RIDED
        CHECKING_A::print();
    //    cout << "; base BALANCE: " << getCompoundInterest();
          }
    
    
    
    
    
    
    
    
    
    
    void virtualViaPointer_1( const ACCOUNT * const ); // prototype
    void virtualViaReference_1( const ACCOUNT & );     // prototype
    
    int main()
    {
    	int product;
    	int quantity;
    	double product1 = 23.84;
    	double product2 = 13.5;
    	double total = 0;
    
    
    
    /////////////////////////////
    /////////////////////////////   step - 1
    /////////////////////////////
    
    cout
    << "\nProduct 1 =   $  " << product1
    << "\nProduct 2 =   $  " << fixed << setprecision( 2) << product2
    << endl << endl;
    
    
    total = total + ( product1 + product2);
    cout << total << endl << endl << endl;
    
    total= 0;    
        
        
        
        
        
        
        
        
        
        
        
       cout << fixed << setprecision( 2 );
    
       // create derived-class objects
       SAVING_A saving_A( "SAVING_A:", 10500, .06 );
       saving_B saving_b( "saving_B:", 10500, .06 );
       CHECKING_A checking_A( "CHECKING_A:", 25, .06 );
       checking_B checking_b( "checking_B:", 25, .06 ); // , 300
    
    // .........................................................................
    // .........................................................................
       cout << " \n\n";
       cout << "                             processed using static binding:\n\n";
    
       saving_A.print();
       cout << "\nearned $" << saving_A.earnings() << "\n\n";
       saving_b.print(); 
       cout << "\nearned $" << saving_b.earnings() << "\n\n";
       checking_A.print();
       cout << "\nearned instrest $" << checking_A.earnings() << "\n\n";
       checking_b.print();
       cout << "\nearned combined $" << checking_b.earnings() 
            << "\n\n";   
       
       
       
        //  I need an Extra virtual call to ***getBalance*** from the
        //  CHECKING_A::CHECKING_A.  I need it to replace the call 
        //  **checking_A.earnings()**  which only return instrest.    
        //  I need the Balance which is $25.00 .  By virtual base-class
        //  reference or pointer.         ......      Thanks in advance
       
       checking_A.print();
       cout << "\nearned instrest $" << checking_A.earnings() << "\n\n";   
       cout << endl << endl; 
       
    
    // .........................................................................
    // .........................................................................
    
      vector < ACCOUNT * > accounts( 4 );  // create vector of 4 base-class pointers
    
       accounts[ 0 ] = &saving_A;          // initialize vector with accounts
       accounts[ 1 ] = &saving_b;
       accounts[ 2 ] = &checking_A;
       accounts[ 3 ] = &checking_b;
    
    // .........................................................................
    // .........................................................................
       cout << "                             dyn-binding > base-class POINTERS:\n\n";
       for ( size_t i = 0; i < accounts.size(); i++ )
          virtualViaPointer_1( accounts[ i ] );
    // .........................................................................
    // .........................................................................
       cout << "                             virtual -- base-class references :\n\n";
       for ( size_t i = 0; i < accounts.size(); i++ )    
          virtualViaReference_1( *accounts[ i ] ); // note dereferencing
    
    
    
    /////////////////////////////
    /////////////////////////////   step - 2
    /////////////////////////////
        //  THIS IS THE GOAL by means given here and above...
        //  I need an Extra virtual call to ***getBalance*** from the
        //  CHECKING_A::CHECKING_A.  I need it to replace the call 
        //  **checking_A.earnings()**  which only return instrest.    
        //  I need the Balance which is $25.00 .  By virtual base-class
        //  reference or pointer.         ......      Thanks in advance
    
    	cout << "Account 1 balance: $25.00 : " << checking_A.earnings()  << endl;
    	cout << "Enter an amount to withdraw from Account 1: ";
    
    	while (!(cin >> product))
    {
                cout << "\nPlease enter ( 1 - 5 ) or to EXIT type -1\n\n" << endl;
                cin.clear();
                    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    cout << "Enter product number 1 - 5 : ";
    }
    
    /////////////////////////////
    /////////////////////////////   step - 3
    /////////////////////////////
    
    	               while ( product != -1 )
    	               {
    		                      switch ( product )
    		                  {
    		                              case 1:
    			                             cout << "\n\nEnter quantity sold1 1 : ";
    			                             cin >> quantity;
                                             cout << endl;
    
    			                             total = total + ( product1 * quantity );
    			                             break;
    
    		                              case 2:
    			                             cout << "\n\nEnter quantity sold 2 : ";
    			                             cin >> quantity;
                                             cout << endl;
    
    			                             total = total + ( product2 * quantity );
    			                             break;
    
    		                              case 3:
    			                             cout << "\n\nEnter quantity sold 3 : ";
    			                             cin >> quantity;
                                             cout << endl;
    
    			                             total = total + ( product2 * quantity );
    			                             break;
    
    		                              case 4:
    			                             cout << "\n\nEnter quantity sold 4 : ";
    			                             cin >> quantity;
                                             cout << endl;
    
    			                             total = total + ( product2 * quantity );
    			                             break;
    
    		                              case 5:
    			                             cout << "\n\nEnter quantity sold 5 : ";
    			                             cin >> quantity;
                                             cout << endl;
    
    			                             total = total + ( product2 * quantity );
    			                             break;
    
    		                      case '\n':
    		                      case '\t':
    		                      case ' ':
                            break;
    
                                 default: // catch any other characters
                  cout << "\nPlease enter ( 1 - 5 ) or to EXIT type -1\n\n" << endl;
                            break;
    		              }
    /////////////////////////////
    /////////////////////////////   step - 4
    /////////////////////////////   Pick up from "quanity sold" == ERROR correction
    
    	   cout << "Enter product number 1 - 5 : ";
    
       while (!(cin >> product))
     {
            cout << "Incorrect entry:  Try again\n" << endl;
            cin.clear();
    
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    
            cout << "Enter product number 1 - 5 : ";
     } //endWHILE
    
    /////////////////////////////
    /////////////////////////////   step - 5
    /////////////////////////////
    
    	}
    	   cout << "\n\n\nT O T A L :    $" << fixed << setprecision( 2 )
    		    << total << endl<< endl<< endl;
    
    
    
    
    
    
       cout << endl;
       cout << endl;
       cout << endl;   
       
    system("pause");
    system ("CLS");
    }
    
    ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////
    //               base-class pointer using dynamic binding
    void virtualViaPointer_1( const ACCOUNT * const baseClassPtr )
    {
       baseClassPtr->print();
       cout << "\n   earned $" << baseClassPtr->earnings() << "\n\n";
    }
    ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////
    //             base-class reference using dynamic binding
    void virtualViaReference_1( const ACCOUNT &baseClassRef )
    {
       baseClassRef.print();
       cout << "\n       earned $" << baseClassRef.earnings() << "\n\n";
    }
    
    
    
    
    
    
    
    
    
    ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////
    //               base-class pointer using dynamic binding
    void virtualViaPointer2( const ACCOUNT * const baseClassPtr )
    {
       baseClassPtr->print();
    //   cout << "\n   combined $" << baseClassPtr->combine() << "\n\n";
    }
    ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////
    //             base-class reference using dynamic binding
    void virtualViaReference2( const ACCOUNT &baseClassRef )
    {
       baseClassRef.print();
    //   cout << "\n       combined $" << baseClassRef.combine() << "\n\n";
    }
    Last edited by sharris; 01-22-2011 at 11:41 AM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    The question appears to be: you are calling earnings(), but you want the balance instead. So why not call getBalance() instead of earnings()?

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Don't ask us to compile your code. Many of us on here usually spot bugs without ever compiling the posted code, and we'll only go that far if we have to. Of course if we have to then many of us will just move along to the next thread. I only compile code on here if I find the topic particularly interesting.

    In this instance I could surely help if I only understand precisely what you were having problems with. Don't say "I need to do xxx", just do it, and then tell us what prevented you from achieving what you were trying to do, including exact error messages.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    tabstop wrote: The question appears to be: you are calling earnings(), but you want the balance instead. So why not call getBalance() instead of earnings()?
    What a great answer! One thing I never got a handle on and that was trying to create user interactions in a console app example that had none. So all last semester long I sent in half done projects.

    Sure, it's easy when switch-case was the example and came build-in. That was a single project, months ago. Never had or saw another with user input since the first three weeks of C++ with switch-case being the only one that seems to be easily re-use somehow. Since joining that been the bulk of my stupid questions, but I never understood the clues until now. Soon I be able to fix the code I posted as promise.

    After all of these months I finally figured out how to insert my old switch-case project into this one and I was scare to death that I might mess something up in the main psrt of the program where only 85% was clear, that leave 15% for a big booboo. I tried many ways before I posted the question. I tried only once this time after I read your reply. WoW! I did the right thing finally.

    Thanks tabstop



    Hello iMalc,

    I thought it was bad to ask someone to run your pre-compile program. I didn't know it apply to source code. If it's a complete one page source and I wanted to help, I would look it over than compile it anyway so that was very foolish and a backward thing to ask. Sorry about that.

  5. #5
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Quote Originally Posted by sharris View Post
    What a great answer! One thing I never got a handle on and that was trying to create user interactions in a console app example that had none. So all last semester long I sent in half done projects.
    So I hope, for your sake, that you're in the same class again, rather than somehow taking the next class along.

    Quote Originally Posted by sharris View Post
    I tried many ways before I posted the question. I tried only once this time after I read your reply. WoW! I did the right thing finally.
    This is ... I don't know what this is. Do you not know what your own functions do? Or if these functions are handed down from your instructor (which from the comments seem somewhat unlikely) did you not read them closely enough to see what they are? This is a good opportunity for introspection: How do you find yourself in a situation where you say "I need to report the balance of a checking account. I can have the checking account do getInterestRate, getBalance, or earnings. I think I'll choose earnings!"? The answer to that question probably won't be pretty, but it's best to be honest with yourself now, and fix it now; for the passing grades-handed-out-like-candy won't last forever.

  6. #6
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    The problem was solved. ... and YES I do know what my function does from top to bottom but I got lost doing my own thing. I base my code off many standard examples but I NEVER use the instructor sample-code provided. Sometime I get confuse than lost in my own version of the code. We all make mistakes. 16 weeks don't make me expert but I to EARN what I get. a (B) that should have been an (A) was not bad for a newbe. I do a ton of other computer work as I go.

    Now I remember why I post... I was using a typo to call with for hours and did not realize it so than started ripping things apart, than I post because I could not find an answer. I was lost.

    PS: YES I'm in the same C++ class with the same instrutor and it was two only project that needed usr-input that drop my grade to a B. I did not feel like going into. All I am saying is I finally see the light all because of one silly mistake.

    Bye
    Last edited by sharris; 01-23-2011 at 02:43 AM.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by sharris View Post
    The problem was solved. ... and YES I do know what my function does from top to bottom but I got lost doing my own thing. I base my code off many standard examples but I NEVER use the instructor sample-code provided. Sometime I get confuse than lost in my own version of the code. We all make mistakes. 16 weeks don't make me expert but I to EARN what I get. a (B) that should have been an (A) was not bad for a newbe. I do a ton of other computer work as I go.

    Now I remember why I post... I was using a typo to call with for hours and did not realize it so than started ripping things apart, than I post because I could not find an answer. I was lost.

    PS: YES I'm in the same C++ class with the same instrutor and it was two only project that needed usr-input that drop my grade to a B. I did not feel like going into. All I am saying is I finally see the light all because of one silly mistake.

    Bye
    So, perhaps the lesson here is to not take the "Bull in a china shop" approach, in future.

    With a "typo" in your code it should not have compiled and your compiler should have been telling you why it didn't compile... probably even giving you a line number and/or the name of the function where the error is. This is valuable information that should not be ignored because it should lead you directly to your errors.

    If programming has taught me nothing else, it has taught me to take a slow and careful approach to problem solving...

  8. #8
    Registered User
    Join Date
    Sep 2010
    Posts
    90
    So, perhaps the lesson here is to not take the "Bull in a china shop" approach, in future.
    I always try to do all the exXX_XX.cpp projects, than I combine stuff from each project. By time the instructor post the sorce code to use I'm in too deep, so I try to relate the instructor files to the other files that are suppose to be related for that weeks assignment. So I should not say never... It just be too late for me to dump some good work that is suppose to be related in the first place. If not, I try hard to fill-in the missing pieces and that can be tough sometimes but when I turn it in the instructor, he knows instantly that I went a mile deeper into matter of the project and he don't deduct points because my code is written differently than the sample-source ... I usually come up with a few extra interesting function to replace the original sample. I'll be on this base-class pointer and reference using dynamic binding for months to come because I plan to understand every thing about it. but now I will miss something in detail maybe next week. If not, I'll forget it..

    With a "typo" in your code it should not have compiled and your compiler should have been telling you why it didn't compile... probably even giving you a line number and/or the name of the function where the error is. This is valuable information that should not be ignored because it should lead you directly to your errors.
    I'm studing Linux, FreeBSD, Web Administration, Web Programming, C++, Java and FASM. It's hard not to make a mistake every now and than. I said "typo", but it was not a typo. I was making a call using the wrong variable which return a zero, than somehow I got confused and I lost my cool .


    If programming has taught me nothing else, it has taught me to take a slow and careful approach to problem solving...
    I'm usually so careful it takes me an extra month to play with any function/program that I really want to learn more about and years for FASM and I never made a mistake with it that could not be found in minutes to recover, so I totally agree! But one thing for sure I rather be writing or vewing or searching code than writing this post.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question bout my work
    By SirTalksAlots in forum C Programming
    Replies: 4
    Last Post: 07-18-2010, 03:23 PM
  2. A question about a question
    By hausburn in forum C++ Programming
    Replies: 3
    Last Post: 04-25-2010, 05:24 AM
  3. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  4. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  5. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM

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