0% found this document useful (0 votes)
3 views1 page

C++ Polymorphism with Animals Example

The document presents a C++ program demonstrating polymorphism through a base class 'Animal' and a derived class 'Dog'. It includes virtual functions for overriding behavior, upcasting from 'Dog' to 'Animal', and downcasting back to 'Dog'. The program checks the success of downcasting and calls specific methods of the 'Dog' class before cleaning up memory.

Uploaded by

roboboysir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

C++ Polymorphism with Animals Example

The document presents a C++ program demonstrating polymorphism through a base class 'Animal' and a derived class 'Dog'. It includes virtual functions for overriding behavior, upcasting from 'Dog' to 'Animal', and downcasting back to 'Dog'. The program checks the success of downcasting and calls specific methods of the 'Dog' class before cleaning up memory.

Uploaded by

roboboysir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#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;
}

You might also like