Search code examples
c++functioninheritanceparent

Pass reference to a parent object to function wanting child object


I have parent class "Entry", which has two childern, Income and Expense. I would like to be able to have a function which works like this:

bool SomeObject::removeEntry(Entry& item, list<Entry> *l)
{
    if (l==&incomeHis)
        return removeIncome(item);
    if (l==&expHis)
        return removeExp(item);
}

Is it possible? function removeExp() requires object of class Expense. Since I am passing it by reference, I know it should be okay, but compiler does not agree.


Solution

  • The compiler is correct in that it can't ensure that every Entry on that line happens to be an Expense.

    You've designed yourself into a corner, so to speak.

    A better design would be to make SomeObject::removeEntry directly perform whatever logic is common to removeIncome and removeExp. Where the logic differs, call a virtual function on item, which can differ between the two types.