Salt_Peter wrote:
Unlike Java, Obj base is not needed since C++ has
a much more resilient and powerful system called templates<>.
I want to notice, that code, written with templates<>, is _compile time
template_ and can not replace (must just works together), of course,
any _runtime templates_.
In order to write class for _runtime template_ you must define a class
with the help of base class interface inheritance (public inheritance).
In order to use any function as _runtime template_, you must use for
all its runtime objects (variables) only pointers or references of its
public base class.
Of course, you must use inheritance _only_ for oo design necessity.
Using typeid? Thats downright wrong, unsafe and complicated.
One can do like this:
void foo(Obj& obj)
{
Shape* sh=dynamic_cast <Shape*>(&obj );
if(sh){ /* Shape-specific code */ }
Color* co=dynamic_cast <Color*>(&obj );
if(co){ /* Color-specific code */ }
}
C++ needs not detect what type a given instance "belongs to". Thats
because an instance is an object. Its self aware. It already knows what
it can and cannot do. Thats the basis of OO design. making everything
an Obj defeats the purpose.
One part of program can create object (and know _real_ object's class),
all other parts of program can use the created object (and know only
object's _base_ class), but some units of the others can use real
object's class again and are forced to cast base class reference to
derived class, and it can be done with dynamic_cast<>.
For instance, there is the design pattern named "decorator" . In order
to get special interface of "decorated" object we are forced to cast to
derived class.
Also there is the design pattern using "pointer to indefinite class"
(for store objects and reorder them in storage (sorting etc)). In order
to get true interface of "stored" object we are forced to cast to
derived class.