"The problem with this code is that if temp points to a Product object, temp-> getday () will be invalid and I don't know how to prevent this."
In the spirit of the question, and if you absolutely do not want to declare / implement getday () in your Product class, as indicated in other answers, you can use dynamic casting to determine the type of runtime of your variable, and only getday () is called if you have There is an instance of Perishable:
Product* pPerishable = new Perishable; Product* pProduct = new Product; Perishable * pActualPerishable; pActualPerishable= dynamic_cast<Perishable *>(pPerishable );
So, try dynamically translating your variable to perishable, and if successful you know you can call getday (). Note that this is no longer polymorphic, but runtime type determination has its uses, especially if you have no control over the interface of the objects you are working on.
source share