Ok, i think I've got it now, i adjusted the "new Animal" to being a "new Dog" and added a call to the destructor and it works now.
Thanks again so much for being patient with me, I know I can be pretty hard to explain things to.
Printable View
Ok, i think I've got it now, i adjusted the "new Animal" to being a "new Dog" and added a call to the destructor and it works now.
Thanks again so much for being patient with me, I know I can be pretty hard to explain things to.
BTW, in real world code, you'd want to check the return value of dynamic_cast (when used with pointers) to see if it's NULL, which means the pointer isn't the right type; or put it in a try/catch block around a dynamic_cast of a reference and catch a bad_cast exception, which also means the reference isn't the right type.
Code:Animal* a = new Cat;
Dog* p = dynamic_cast<Dog*>( a );
if ( p == NULL )
{
cout << "Oops, I guess 'a' isn't really a Dog!" << endl;
}
Animal& b = *a;
try
{
Dog& r = dynamic_cast<Dog&>( b );
}
catch ( std::bad_cast& e )
{
cout << "Oops, I guess 'b' isn't really a Dog!" << endl;
}
Your destructor's should be virtual.
Thanks guys for all the help,
I have one last question on the subject,
let's say i have Dog, object, but want it to behave like a Cat object, assuming they're both on the same hierarchy level, would it be more efficient to use casting at all, or just destroy the Dog, and recreate the object as a Cat, and go with it from there?
It is not so much a matter of efficiency as a matter of correctness: you have a dog, but you want a cat, so if you can only have one animal, then you must get rid of the dog and then get the cat. You cannot turn the dog into a cat.Quote:
Originally Posted by Aaronugio
well it's not so much that i want the Dog to BE a cat so much as i want it to be able to perform a couple of Cat functions
or would it be more effective to just write the two or so Cat functions as protected functions within the parent Mammal Class
Then you need to rethink your design.Quote:
Originally Posted by Aaronugio
Why would a Dog need Cat functions? If it needs that, then the design should be flawed.
You should try to keep functionality that both classes need in a common base class, but it should also be something one can expect from that class. Like a Dog not meowing.
So basically, you want a Dog that's afraid of water and says "Meow"? :confused:
>> So basically, you want a Dog that's afraid of water and says "Meow"?
Sort of like how Mr. Ed can talk like a human, neigh?