This question may not be helpful to some but I'll ask anyway. I've hit a bit of a object orientated design issue. Making a RPG and the user gets to choose their own class i.e warrior/rogue/etc.
Sample:
int main()
{
CharacterP *cPntr = new CharacterP // creates base pointer
cPntr->createClass(cPntr, "Warrior"); // creates a new Warrior object which cPntr is now
//pointing to.
cPntr->printCharacterName(); //will print the warriors print name function
return 0;
};
class CharacterP
{
void createClass(CharacterP* &samp, string choice)
{
if (choice == "Warrior")
samp = new Warrior;
// other classes go here...... i.e Rogue, Mage
}
virtual void printCharacterName() //I don't want this function here
//as this function will never be used, however it is
//needed as the type of pointer for cPntr is CharacterP
//which is the base of warrior.
{
std:: cout << "i don't want this function here, although it is required;
}
};
class Warrior : public CharacterP
{
virtual void printCharacterName()
{
std::cout << "you printed warrior";
}
};
The main problem is the way I've designed this: If I want to use a Warrior
function, I also have to define it into the base class CharacterP
. When i start branching this out and adding more classes i.e Mage/rogue its going to be a maintenance nightmare as the base class would have a lot of functions that won't be used at all.
Questions:
Why does this happen?
Why does the base class also need to have the same function even though the derived function is virtual?
What is a more efficient way of doing what i am doing? (giving the user the ability to create any classes they want i.e Warrior,Warrior,Mage/Rogue,Mage,Mage) maybe a way to create a warrior object with its own pointer which can be repeated so 3 warrior objects are created and can be used at runtime.
cPntr
to a new character and then reassign this pointer to a new Warrior without deleting or keeping the first pointer. I suspect yourcreateClass
wants to be static so you can call it directly. However, you're probably better following the other answers and using constructors, but in case you don't you should be aware of this. \$\endgroup\$ – T. Kiley Feb 24 '15 at 12:48