Base class pointer accessing derived class method

I am writing a Bank Account management system and have an abstract base called AccountsFactory. I use a static method AccountsFactory::create(int option) which returns AccountsFactory*, which is an instantiation of one of 5 derived classes. Then I call the a process method with belongs to the derived class via
a static_cast. This in turn call a base class process method, then continues to perform the individual behavior needed for the derived class. All this is working fine.

My problem is that I am having to put switch statements in the code that processed each menu option. This is bad because if the number of options on the menu increases, the switch needs reproducing and if the number of accounts the bank offers all these switch statements need updating. So, two reasons why I think this situation is not good

But I don't know how to resolve the situation.

Here is some pseudo code;

Get an option from the main menu.
Example: Create New Account
Get an option from create new account menu
Use AccountsFactory to create the appropriate account object
call object.process() method;

This is the code I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
        Menu::accounts();
        int accountType = Menu::accountsOption();
        AccountsFactory* account = AccountsFactory::create(accountType);
        switch(accountType){
        case AccountsFactory::CurrentAccount:
            static_cast<AccountCurrent*>(account)->process();
            break;
        case AccountsFactory::SavingsAccount:
            static_cast<AccountSavings*>(account)->process();
            break;
        case AccountsFactory::Fixed1Account:
            static_cast<AccountFixed1*>(account)->process();
            break;
        }


and would like to replace the switch statement with

(determine type of derived object)* ->process()

I think the word you are looking for is "virtual".

See
http://www.cplusplus.com/doc/tutorial/polymorphism/
under "Virtual members"
Last edited on
Thank you.

There is so much to remember about inheritance and polymorphism.

That worked a treat.

1
2
3
4
5
void OptionCreateAccount::process(){
        Menu::accounts();
        AccountsFactory* account = AccountsFactory::create(Menu::accountsOption());
        account->process();
}


I have managed to tidy up the code nicely
Last edited on
Topic archived. No new replies allowed.