今後のプログラムでは、公的機能は同じで私的機能が異なる猫と犬のクラスを派生させた動物クラスがあります。実行時にどの動物を作成するかをユーザーに決定させたいと思います。私は私がおおよそ欲しいものを示す簡単な例を作りましたが、それは明らかに機能しません。これを解決する方法がわかりません。ご協力をお願いします。
#include <cstdio>
class canimal
{
public:
int sound()
{
std::printf("...\n");
return 0;
}
};
class cdog : public canimal
{
public:
int sound()
{
std::printf("Woof!\n");
return 0;
}
};
class ccat : public canimal
{
public:
int sound()
{
std::printf("Mieau!\n");
return 0;
}
};
int main()
{
canimal *animal;
cdog *dog;
// I would like to let the user decide here which animal will be made
// In this case, I would like the function to say "Woof!", but of course it doesn't...
animal = new cdog;
animal->sound();
// Here it works, but I would like the pointer to be of the generic class
// such that the type of animal can be chosen at runtime
dog = new cdog;
dog->sound();
return 0;
}