Let's say we have a template class Area
, which has a member variable T area
, a T getArea()
and a void setArea(T)
member functions.
I can create an Area
object of a specific type by typing Area<int>
.
Now I have a class Rectangle
that inherits the Area
class. Since Rectangle
itself is not a template, I cannot type Rectangle<int>
.
How do I specialize the inherited Area
type for Rectangle
objects?
EDIT: Sorry, I forgot to clarify – my questions is whether it is possible to inherit Area without specializing it, so it is not inherited as Area of ints but as Area Rectangle can specialize the types for.
Best Answer
For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.
Specifically,
Area
is not a template class, but a class template. That is, it is a template from which classes can be generated.Area<int>
is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would beArea<char>
. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.Since
Area
is not a class, you cannot derive the classRectangle
from it. You only can derive a class from another class (or several of them). SinceArea<int>
is a class, you could, for example, deriveRectangle
from it:Since
Area<int>
andArea<char>
are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):However you have to specify which classed to derive from when you define
Rectangle
. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.What you can do is to make
Rectangle
a template as well. If you writeYou have a template
Rectangle
from which you can get a classRectangle<int>
which derives fromArea<int>
, and a different classRectangle<char>
which derives fromArea<char>
.It may be that you want to have a single type
Rectangle
so that you can pass all sorts ofRectangle
to the same function (which itself doesn't need to know the Area type). Since theRectangle<T>
classes generated by instantiating the templateRectangle
are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:If it is important that your generic
Rectangle
is derived from a genericArea
you can do the same trick withArea
too: