Dynamic Binding Flashcards
Why can’t a derived pointer reference a base object?
A base object does NOT have the memory for the derived members. The integrity of the data cannot be maintained.
What is the syntax for downcasting with a constant reference?
const derived * ptr = dynamic_cast(& const_base_reference);
OR
const derived * ptr = dynamic_cast(& const_derived_obj);
What is the syntax for downcasting with a base pointer?
derived * ptr = dynamic_cast(base_class_ptr);
// Check to make sure it has memory if(ptr) data_member = new derived(*ptr);
What is downcasting?
Downcasting is the act of using a cast to type convert a base class pointer or const reference to a derived pointer at run time.
Where does upcasting take place? And what is the syntax?
In the argument list.
Syntax: void function(base * pointer) { p->other_function(); // Waits till run-time to perform operation and call the derived function because a base class IS a derived }
main derived * ptr2 = &obj; // Creates a derived pointer to an object function (&obj); // Passes in the object
What is upcasting?
Upcasting is where you can have a base class pointer point to anything in the hierarchy. No type conversion takes place because a base IS its child. A base class pointer points to a derived or base class object.
Why is RTTI important?
Constructors cannot be virtual and type conversion without a cast will result in a compilation error because the correct object is not being referenced at compile time. So, it is important to wait until runtime using the dynamic_cast operation to determine which object is being pointed to.