I think the animalBase to cat works because the base class still knows about the derived class. |
As coder777 says, this isn't right. The base class doesn't know anything about the derived class.
It is the
cat
object that you created, that contains the information about what class it is. This is the
run time type information (RTTI) that coder777 mentions. When an object is created, and it has virtual functions, then the RTTI is automatically created and stored as part of the object.
If you have an
animal
pointer, and the pointer is pointing to a
cat
object, then when you use that pointer to call a virtual method like
name()
, then the behind-the-scenes code looks at the RTTI, discovers that the object is actually a
cat
, and calls
cat::name()
- even though the pointer you used to access the object is only an
animal*
.
We call this
run-time polymorphism - that is, the ability of the program to determine at run-time what the type of the object really is, even if you're using a pointer of a base class type.
When I am placing the dynamic cast into a pointer object, shouldnt that pointer need to be of the same type as the object, so example in my code below. |
No. It just needs to be a
compatible pointer type. By definition, a
cat
object is also an
animal
object, so it is a compatible type. Any attempt to treat the object as an
animal
will work, because
cat
has all the properties of
animal
.
from what I remember if you set a pointer equal to another pointer without the **, the second pointer simply gets whatever is in the first pointers memory, is that the same with this? |
Both pointers are pointing to exactly the same bit of memory, yes.
Remember: a pointer is just a number, and that number is a memory address. If you set two pointers to store the same value, then they are both storing the same memory address, which means they're both pointing to the same bit of memory.
Do I end up with a animal pointer pointing at the cat object on the heap? And then and ani pointer still pointing at the cat object too on the heap. |
Yes. At the end of your code,
ani
,
animalBase
and
catDerived
all point to exactly the same object, and that object is a
cat
.