Your question hits on one of the most important parts of object-oriented programming: polymorphism.
Derived
is a subtype of Base
. That means that everything that Base
can do, Derived
can also do. Often, Derived
is more specific than Base
: it works on a subset of what Base
does, but it does that subset much better than what Base
does.
Think about an example.
Think about writing a graphics program. You might have a class, ClosedShape
, and a method inside it, fill()
. It's possible to create a very generic method that can fill any closed shape... but usually, that method will take memory, and it might be slow.
You might have another class, Square
. Now, filling squares is very easy and very fast: it's two nested for loops. Since Square
does everything that ClosedShape
does, it can inherit from ClosedShape
.
Why is polymorphism important? Think about many different kinds of ClosedShape
: triangles, hexagons, and so forth. If you want to fill all of them, just do:
for (i=0; i<num; i++) {
cs[i].fill();
}
They all will use their own version of fill()
!