#include <iostream>
#include <string>
using namespace std;
// Base class
class Animal {
public:
virtual void speak() const { // Virtual function for polymorphism
cout << "Animal speaks" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void speak() const override { // Override the base class method
cout << "Dog barks" << endl;
}
void fetch() const { // Specific method for Dog
cout << "Dog fetches the ball!" << endl;
}
};
int main() {
Animal* animalPtr = new Dog(); // Upcasting: Animal pointer to Dog object
// Downcasting: Convert Animal pointer back to Dog pointer
Dog* dogPtr = dynamic_cast<Dog*>(animalPtr);
if (dogPtr) { // Check if the downcast was successful
dogPtr->speak(); // Call Dog's speak method
dogPtr->fetch(); // Call Dog's specific method
} else {
cout << "Downcasting failed." << endl;
}
delete animalPtr; // Clean up memory
return 0;
}