Get dat cat to Purr()

I really want that Cat to Purr()!

//Justin
#include 
using namespace std;

class Mammal
{
public:
	virtual void Speak() const {cout << "Mammal Talk!"; }

};

class Cat : public Mammal
{
public:
	void Speak() const { cout << "Meow!"; }
	void Purr() const { cout << "RRRRRRRRRRrr"; }
};

class Dog : public Mammal
{
public:
	void Speak() const { cout << "Wolf!"; }
};

int main()
{

	Mammal * pMammal;

	pMammal = new Cat;

	Cat * lol = dynamic_cast<Cat*> (pMammal);

	lol->Purr();
        cout << "The Game." << endl;

	cin.get();
	return 0;
}

Cat is a derived class from Mammal and overrides the Speak() function. Since all Mammals know how to Speak(), this is polymorphic and makes sense in our code. What if I want a Cat object to know how to code, but not another derived Mammal class like Dog? You can percolate Purr() up into Mammal but that’s bad practice, since it doesn’t apply to Dog.

What you can do is use dynamic_cast to safely cast the pointer as a pointer to a Cat object. Dynamic_cast provides a run-time safety check to ensure that it is indeed a pointing to a valid Cat object.

Cat * paw = dynamic_cast<Cat* > (pMammal)

paw->Purr();

Hax!!

Why would you want to do this? I don’t know. It’s not very polymorphic.

Leave a Reply

Your email address will not be published. Required fields are marked *