Get dat cat to Purr()

I really want that Cat to Purr()!

using namespace std;

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


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

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

int main()

	Mammal * pMammal;

	pMammal = new Cat;

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

        cout << "The Game." << endl;

	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)



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 *