What is the purpose of creating a pointer of the base class to a class that inherits from it?
For example:
[cpp]class Inherits : public Base {};
Base * Inherited = new Inherits();[/cpp]
I normally use it so I can store all instances of any class derived from the baseclass in the same container.
[editline]07:44AM[/editline]
It's called polymorphism btw.
Are you asking what is the point of polymorphism? Because I would hope that is already clear to you.
Being able to downcast is an important feature of polymorphism, and the derived class should still be able to act as another instance of the base class, even if it's functions are overloaded.
It's mainly used for polymorphism which in a nutshell lets you treat a bunch of similar types as one abstract type. For example
[cpp]
class Shape
{
virtual void draw() { /* Blank */ }
};
class Square : public Shape
{
void draw()
{
//Code to draw a Square here
}
}
class Triangle : public Shape
{
void draw()
{
//Code to draw a triangle here
}
}
int main()
{
Shape* baseShape = new Triangle();
baseShape->draw(); //Calls Triangles version of draw()
delete baseShape
baseShape = new Square();
baseShape->draw(); //Calls Squares version of draw()
//A more advanced example
std::vector<Shape*> shapes;
shapes.push_back(new Triangle());
shapes.push_back(new Square());
shapes.push_back(new Triangle());
//Will draw a Triangle, then Square then another Triangle.
for(std::vector<Shape*>::iterator shape = shapes.begin(); shape != shapes.end(); ++shape)
{
(*shape)->draw();
}
}
[/cpp]
The other advantage is that if you make another class, say Circle. You don't have to modify your loop to accommodate it.
[QUOTE=Cathbadh;18694847]Are you asking what is the point of polymorphism? Because I would hope that is already clear to you.
Being able to downcast is an important feature of polymorphism, and the derived class should still be able to act as another instance of the base class, even if it's functions are overloaded.[/QUOTE]
You're right, I was looking at the whole thing in totally the wrong way and now I have no idea why. Thanks t0rento as well.
A Dog is-a Animal. A Cat is-a Animal.
A Shelter contains a list of Animals. Animals can eat(). Now you can say eat() on each Animal in the list without caring whether it is a Dog, a Cat, or any other Animal you might later add.
[QUOTE=nullsquared;18700614]A Dog is-a Animal. A Cat is-a Animal.
A Shelter contains a list of Animals. Animals can eat(). Now you can say eat() on each Animal in the list without caring whether it is a Dog, a Cat, or any other Animal you might later add.[/QUOTE]
Excellent analogy, +1
Sorry, you need to Log In to post a reply to this thread.