0
votes

I was told that a base class pointer can point to any derived types of that base class. However, I need to access this derived class even though the argument is calling a pointer to base class.

Here Meeting is the derived type, ListItem is the base type, CompareByInsertKey is a mandatory purely virtual function in ListItem overriden by Meeting::CompareByInsertKey, and Meeting has a structure called thisdate with a member year. In this instance, item_in_list would be a Meeting type but apparently the pointer still works even though it's a derived type.

int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
    int compare = (*item_in_list).thisdate.year;
    return compare;

}

How do I allow this method to take in a derived or base class argument and allow it to use derived class members?

In other words, I need to access a derived type's private members in a method of that derived type. The problem is that the CompareByInsertKey function must take a base class pointer in order to override the purely virtual ListItem::CompareByInsertKey

Thanks, if you need any more information, please let me know

2

2 Answers

2
votes

You should use dynamic_cast, like this:

int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
    Meeting *meeting = dynamic_cast<Meeting*>(item_in_list);
    // dynamic_cast returns a null pointer if the passed pointer is not
    // of the requested type
    if(meeting == 0) {
       ...
    } 
    int compare = meeting->thisdate.year;
    return compare;
}
0
votes

The way you have it set up today, the only way I can see is to do a type check and cast using dynamic_cast. This ensures that mismatched types are not passed in.

int Meeting::CompareByInsertKey(ListItem* item_in_list)
{
    Meeting* meeting = dynamic_cast<Meeting*>(item_in_list);
    if(NULL != meeting)
    {
        int compare = meeting->thisdate.year;
        return compare;
    )
    else // return error value
}