I spent hours and hours looking online but none had the same problem as me. Basically, I have a base class called MainShop and it has 3 derived classes which are SwordShop, SpellBookShop and BowShop. I want the base class to be able to call a function from one of the derived classes but no matter what i do, it doesn't seem to work! Here is my code:
#include "MainShop.h"
//BaseClass cpp
void MainShop::EnterShop(Hero& hero)
{
//Display Choices
switch (choice)
{
//Swords
case 1: SwordShop::soldierShop(hero);//DOES NOT WORK!!
break;
case 2: SpellBookShop::MageShop(hero);//Staffs
break;
case 3: BowShop::ArcherShop(hero);//Bows
break;
default: cout << "Error!, Please try again.";
MainShop::EnterShop(hero);
}
}
I have two other derived classes, but its basically the same concept. I have a function in one of the derived classes and i would like to call it from the base class. This is one my derived classes:
//SwordShop derived cpp
#include "SwordShop.h"
void SwordShop::soldierShop(Hero& hero)
{
/* some code here*/
}
It's not a good design to select specific sub-class instance in super-class methods, e.g., by dynamic_cast
, due to runtime overhead, and future maintenance, etc.
You can offload the burden of such switch-case logic to virtual functions which are designed by the language to call a specific instance via base class pointer/reference.
For example:
class MainShop
{
public:
virtual void EnterShop(Hero &hero) = 0;
};
class SwordShop: public MainShop
{
void EnterShop(Hero &hero)
{
soldierShop(hero);
}
};
class SpellBookShop: public MainShop
{
void EnterShop(Hero &hero)
{
MageShop(hero);
}
};
int main()
{
...
MainShop *shop = new SwordShop;
// calling soldierShop
shop->EnterShop(hero);
..
shop = new SpellBookShop;
// calling MageShop
shop->EnterShop(hero);
...
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments