Re: Polymorphism - accessing derived class data members
Alexh <alexh1@sbcglobal.net> wrote:
I have implemented various graphic elements (classes) which are
derived from a base class. The primary advantage of this is that any
operations on the derived classes can be done via virtual functions
and thus the code that performs the operation does not have to
identify the element (avoids a huge switch statement for every
operation). This is typical polymorphism.
The problem I'm having is modification of existing elements. The
properties of the elements are set up from a dialog (specific to each
type of element) which executes a new statement to create the element.
Since the pointer for element is the base type (and not the derived
class type), it cannot be used to access the derived class variables
which is necessary if the user wants to modify the element options for
an existing element.
If you know somehow that the base class pointer you hold is actually a =
pointer to a specific derived class, you can just cast it.
Later, a user may need to modify an existing Dog. Currently, I do this
by opening DogDlg from a modify menu and on IDOK I delete the
exisiting Dog and simultaneously create a new one from the new dialog
data (delete/replace is transparent to user). The problem arises when
there is more than one Dog because then the dialog may not reflect the
correct data for the selected element (dialog reflects last useage).
Ideally, I would like to have the dialog data reflect that actual data
associated with the Dog I am modifying.
How do you know that the currently selected element is actually a Dog, =
suitable for editing with DogDlg?
Some other methods that were suggested to me which won't work -
1. Change base class pointer to a derived class pointer. i.e. CDog*
pElement = new .... defeats purpose of polymorphism
Not at all. Code designed to work with generic CElement can continue to =
do that. Code that is specific to CDog (such as DogDlg) is very much =
justified in wanting a CDog* pointer. Nothing says you must lose type =
information immediately after creating a new instance.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not =
necessarily a good idea. It is hard to be sure where they are going to =
land, and it could be dangerous sitting under them as they fly overhead. =
-- RFC 1925