another homework question...

This is a discussion on another homework question... within the C++ Programming forums, part of the General Programming Boards category; Looking for an improvement to my code. It's a little much to post, but here's the idea: I have a ...

  1. #1
    Registered User skillet's Avatar
    Join Date
    Feb 2002
    Posts
    20

    Talking another homework question...

    Looking for an improvement to my code. It's a little much to post, but here's the idea:

    I have a class --"savingsAccount"--

    in the main function I declare three objects with savingsAccount.

    I'd like to loop through some functions on my savingsAccount objects "dynamically". That is, if I do a

    for (i = 0, i <= 3, i++)

    it works fine, but what if I add 3 more objects? I don't want to go change the for loop everytime an object is declared. My approach has been to add a static count to the class that is increased each time an object is declared. I can then loop from 0 to "< savingsAccount::count". good? bad? ideas?

    Second half of the same problem is getting the object names inside the loop. if I have:

    savingsAccount Saver1;
    savingsAccount Saver5;
    savingsAccount Saver7;
    ...

    what can be done inside the for loop so that a different object is chosen each loop, and so I don't have to go change the for loop code when a new object is declared? I'm thinking there is a pointer solution here somewhere, but the solution has evaded me so far...

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    for (i = 0, i <= 3, i++)

    Sorry, but this won't loop 3 times, it loops 4 times (0,1,2,3 = 4)

    If you need a "dynamic loop", use a variable instead of a constant:

    int NrOfLoops=3;
    for (i = 0, i < NrOfLoops, i++)


    You can change this variable while the program is running if you add more objects.

    To your second question: Yes, pointers are the solution. Use new to allocate memory for the objects:

    savingsAccount* MyPointer;
    MyPointer=new savingsAccount[NrOfLoops];
    ...
    delete[] MyPointer;

    Remember to deallocate the memory useing delete
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    I would declare another class to hold the collection of objects.

    class account
    {
    //whatever
    };

    class Bank
    {
    //collection of accounts.
    //whatever
    };

    Depending on what container you use to hold the collection of accounts in the Bank classs you may want to use a count variable in Bank like you proposed, although if you use a container class from STL, like a vector or a list, etc., many of them have built in members to do this for you.

    If you want to identify a given account by name within a loop it is best to embed the name as a member variable within the struct/class.

    let's say you have a simple array of accounts, and that you have a counter variable in Bank to keep track of the number of accounts in Bank. Then to refer to each account, just use the subscript variable on the array name as you usually would. If you want to put more accounts in the Bank than can be stored in the array, you have a bit of problem, however, although it can be overcome. With this approach space for each account in the array is set aside when the Bank object is declared in the program, so you don't need to use the new operator up front (if you want to change the size of the array, then you might need to use the new operator, though). You can avoid all this hassle by using a self-expanding array, like the vector class in STL.

    If you use a routine list (object) to hold the collection of accounts in Bank, then you will probably need to use the new operator to declare each new account that is added to the list, unless, of course, the list is an object of the list class in STL, in which case the stuff with the new operator is done behind the scenes for you, once you learn the correct terminology.
    Last edited by elad; 04-03-2002 at 10:11 AM.

  4. #4
    Registered User skillet's Avatar
    Join Date
    Feb 2002
    Posts
    20

    Smile thanks...

    (mixed reply to both magos and elad)

    OK... the terminoligy is starting to get just out of my reach...

    I am guessing that "STL" is a collection of C++ classes available, but I am not familiar with those, and I suspect coming up with a solution provided by classes programmed outside of the scope of my *class* (acedemic here), would not be an acceptable solution.

    yeah... loops 4 times. my bad, but it was just for an example. Thanks.

    The pointer solution looks like it declares one pointer to an array of accounts... how would I reference the second account with that pointer?

    I like that solution magos, but due to the restrictions on this assignment, I don't think that will work. The problem is we have multiple constructors. One object is declared with a name and balance in the data, one with only a name, and one with no name and no balance. I don't think I can use all three constructors when one array of savings accounts is declared... am I wrong?

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    STL is commonly used to refer to the Standard Template Library, and it is indeed a collection of classes for use in standardized C++ code, although many older compilers do not have it available as part of their software.

    when arrays are declared using the new operator the new operator can only use the default constructor for the class.

    Many people will say that the following lines declare an array of type savingsAccount on the heap(free store) using dynamic memory. The name of the array is MyPointer, and it has NrOfLoops elements within the array. Each element in MyPointer has been declared using the default constructor.

    savingsAccount* MyPointer;
    MyPointer=new savingsAccount[NrOfLoops];


    Let's say you have three constructors for savingsAccount appropriate for the following examples:

    int main()
    {
    savingsAccount savings1;
    savingsAccount savings2("chelsea");
    savingsAccount savings3("mercury", 4532);

    const int MAX = 3;

    savingsAccount Bank1[MAX];

    Bank1[0] = savings1;
    Bank1[1] = savings2;
    Bank1[2] = savings3;

    int i;
    for(i = 0; i < MAX; i++)
    {
    cout << Bank1[i].name << " : " << Bank1[i].balance << endl;
    }

    cout << "now for a new bank. How many accounts to you want" << endl;
    cin >> i;

    savingsAccount * newBank = new savingsAccount[i];//uses default contstructor

    int j;

    //demonstrate that the default constructor was used in newBank
    for(j = 0; j < i; j++)
    {
    cout << newBank[i].name << " : " << newBank[i].balance << endl;
    }

    //now get user input to put in newBank;
    char dummy[80];
    for(j = 0; j < i; j++)
    {
    cout << "enter name " << endl;
    cin >> dummy;
    strcpy(newBank[i].name, dummy);

    cout << "enter balance" << endl;
    cin >> newBank[i].balance;
    }

    //etc.

  6. #6
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145

    Re: thanks...

    Originally posted by skillet
    The problem is we have multiple constructors. One object is declared with a name and balance in the data, one with only a name, and one with no name and no balance. I don't think I can use all three constructors when one array of savings accounts is declared... am I wrong?
    I believe you're right. Do you have to use constructors to init the data? You could use public functions:
    Code:
    
    savingsAccount* MyPointer;
    int NrOfObjects=4;
    MyPointer=new savingsAccount[NrOfObjects];
    MyPointer[0].FakeConstructor1();
    MyPointer[1].FakeConstructor2("Chelsea");
    MyPointer[2].FakeConstructor1();
    MyPointer[3].FakeConstructor3("Mercury", 4532);
    ...
    delete[] MyPointer;
    

  7. #7
    Registered User skillet's Avatar
    Join Date
    Feb 2002
    Posts
    20

    void main()

    How about this.... I got this compiling, and the output is what I want. It is to a point now that it should be simple to add for loops at obvious locations--calculateNewBalance and cout. My class already contains a count of how many objects have been declared--each time I declare an object the total number of accounts is incremented, then I use that result for the account number.

    I left out my class def... didn't think that is overly important. I overloaded "<<" to print out the data, and the functions are fairly self descriptive.

    note:
    It looked like I could have used "delete [] savingsPtr;" at the end, but it produces a warning at compile, since savingsPtr was not declared with a "new" assignment. Also, If I try to delete any of the pointers that were not assigned, it brings up a run-time error.



    void main ()
    {

    // only limit to number of accounts is the array set here.
    SavingsAccount *savingsPtr[10];

    // 1) Declare 3 objects:
    // Saver1: Margaret Olson with a balance of $2,000
    // Saver2: Debra Baxter with no balance
    // Saver3: account with no name, no balance
    savingsPtr[1] = new SavingsAccount ("Margaret","Olson",2000.00);
    savingsPtr[2] = new SavingsAccount ("Debra","Baxter");
    savingsPtr[3] = new SavingsAccount;

    // 2) Set Baxter's balance to $5,000
    savingsPtr[2]->setBalance(5000.00);

    // 3) Set Account 3 as "Arturo Ortiz"
    // with a balance of $10,000
    savingsPtr[3]->setName("Arturo","Ortiz");
    savingsPtr[3]->setBalance(10000.00);

    // 4) Calculate a new month balance for everyone
    savingsPtr[1]->calculateNewBalance();
    savingsPtr[2]->calculateNewBalance();
    savingsPtr[3]->calculateNewBalance();

    // 5) Show all the data for all of the accounts
    fileout << *savingsPtr[1] << *savingsPtr[2] << *savingsPtr[3];

    // 6) change the annual interest rate
    SavingsAccount::setInterestRate(10.0);

    // 7) Calculate a new month balance for everyone
    savingsPtr[1]->calculateNewBalance();
    savingsPtr[2]->calculateNewBalance();
    savingsPtr[3]->calculateNewBalance();

    // 8) Show all the data for all of the accounts
    fileout << *savingsPtr[1] << *savingsPtr[2] << *savingsPtr[3];

    // note: before dereferencing the pointers, the destructor
    // was NOT called-- equals wasted memory.
    delete savingsPtr[1];
    delete savingsPtr[2];
    delete savingsPtr[3];

    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question About My Homework Pls Help Me İmmediately
    By jennyyyy in forum C Programming
    Replies: 27
    Last Post: 03-13-2008, 12:40 PM
  2. quick question
    By surfingbum18 in forum C Programming
    Replies: 5
    Last Post: 12-04-2007, 06:16 AM
  3. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 05:22 AM
  4. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM

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