class Product
{
...
}
class Perishable : public : Product
{
public:
int getday();
}
int main()
{
Product *temp;
//due to some coding
//temp could point to either Perishable object or Product object that is determine //during runtime
cout<< ((Perishable*)temp)->getday() ;// is there other way to achieve this typecasting seems dangerous
The problem with this code is that if temp point to a Product object, temp->getday() would be invalid and i do not know how to prevent this from happening. If due to some circumstances , i am only allowed to have getday() in Perishable but not in Product, how could i check whether temp is pointing to a perishable object or a Product object?
Some help would be appreciated/
}
“The problem with this code is that if temp point to a Product object, temp->getday() would be invalid and i do not know how to prevent this from happening.”
In the spirit of the question, and if you absolutely do not want to declare/implement getday() in your Product class as mentioned in the other answers, you can use dynamic cast to determine the runtime type of your variable, and then only call getday() if you have a Perishable instance:
So, try to dynamic cast your variable to a Perishable, and if successful then you know you can call getday(). Note this is no longer polymorphic, but determining the type at run time has its uses especially if you don’t have control over the interface of the objects you are working on.