cast child class into parent class
this is just a sample code
class parent{ //abstact class
//pure virtual function
virtual fun=0;
}
class child : parent{
fun;
}
main()
{
//what should i do here,so i can add parent in vector
attach(child);
}
void attach(parent* p){
vector.push_back(p); //want to add reference of parent into vecotr
}
and i want to cast child into parent but not able to do please 开发者_StackOverflowany one help me?
The child instance has the type parent (and child). If you have an instance of child, there is no extra instance of parent lying around. You can use a child instance wherever a parent instance is required. There is no need to cast.
Class cast excetion :
Occurs when u try to cast a parent class into child class.
Reason: the parent class has not everything that a child class has, on the other hand a child has everything that a parent has so you can cast a child into parent.
In other words, the instance that you want to downcast must be an instance of the class that to which you are downcasting.
精彩评论