you may be changing the values of a's members, but a is still an animal and not a lion.
Polymorphism can only be used through pointers and references. For example,
std::unique_ptr<animal> a(new lion(0, 0));
Now a is a pointer to an animal, but the object being pointed to is a lion.
In other words, arr should be an array of pointers to animals, not merely an array of animals. The code you commented out was actually correct. You need to dynamically allocate a lion or tiger and then assign it to one of the pointers in arr.
#include <iostream>
#include <string>
class Animal {
protected:
int weight {}, power {};
public:
Animal() {}
Animal(int w, int p) : weight(w), power(p) {}
virtual std::string getType() const = 0;
virtualint getPower() const {return power * weight; }
};
class Lion : public Animal {
public:
Lion(int w, int p) : Animal(w, p) {}
std::string getType() const { return"Lion"; }
};
class Tiger : public Animal
{
public:
Tiger(int w, int p) : Animal(w, p) {}
std::string getType() const { return"Tiger"; }
};
int main()
{
size_t n {};
std::cout << "How many animals: ";
std::cin >> n;
auto arr {new Animal*[n]{}};
std::string which;
int w {}, p {};
for (size_t i = 0; i < n; ++i) {
std::cout << "Animal type (l or t): ";
std::cin >> which;
std::cout << "Weight power: ";
std::cin >> w >> p;
if (which[0] == 'l')
arr[i] = new Lion(w, p);
else
arr[i] = new Tiger(w, p);
}
for (size_t i = 0; i < n; ++i)
std::cout << arr[i]->getType() << " " << arr[i]->getPower() << '\n';
for (size_t i = 0; i < n; ++i)
delete arr[i];
delete[] arr;
}
How many animals: 3
Animal type (l or t): l
Weight power: 12 23
Animal type (l or t): l
Weight power: 23 45
Animal type (l or t): t
Weight power: 2 3
Lion 276
Lion 1035
Tiger 6