Let's say I have a base class and multiple derived classes and I want to avoid having multiple variables/functions for every derived class type.
The only way I found to realize this is using up-/downcasting. But especially downcasting is often considered bad practice - so whats the way to go?
Example:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
class Animal{
protected:
Animal(std::string val) { name = val; }
public:
virtual ~Animal() = default;
std::string name;
};
class Cat: public Animal {
public:
Cat(std::string name) : Animal(name) { }
~Cat() = default;
void purr();
};
class Dog: public Animal {
public:
Dog(std::string name): Animal(name) { }
~Dog() = default;
void bark();
};
void pet(Animal *animal) {
if (!animal)
return;
if (dynamic_cast<Cat*>(animal))
std::cout << "petting my cat " << animal->name << std::endl;
else if (dynamic_cast<Dog*>(animal))
std::cout << "petting my dog " << animal->name << std::endl;
};
int main()
{
Animal *currentPet = new Cat("Lucy");
pet(currentPet);
// after many joyful years - RIP
delete currentPet;
currentPet = new Dog("Diego");
pet(currentPet);
delete currentPet;
currentPet = NULL;
return 0;
}
Is this totally fine or still considered bad design/practice?