zRaze said:
Scenario:
I have a base class called "BaseCls", and two derived classes called
"DerCls1" and "DerCls2"
I declare a variable -
BaseCls *MyClassObj;
I have some code -
If( Condition )
{
MyClassObj = new DerCls1;
} else {
MyClassObj = new DerCls2;
}
How can I tell if MyClassObj is pointing to a DerCls1 or DerCls2
object?
Thanks in advance...
If you have to make that distinction you probably have a poor design. When
you have a pointer to a base class which really points to a derived class,
you are using polymorphism. As Jakob implied, the best way to deal with
polymorphism is to call a virtual function which does the right thing no
matter what type it is. This scheme is efficient and maintainable. (For
instance it would be easy to add a DerCls3 later.) If it is impossible
because you can't implement any such virtual function then maybe
polymorphism was the wrong approach in the first place.
A couple of other points: you should probably put a do-nothing virtual
destructor in the base class:
virtual ~BaseCls() {}
to make sure possible destructors in derived classes are called properly.
Also, whenever you use new() you must use delete() to avoid a memory leak
and you must use it only once to avoid undefined behaviour. This can be a
source of problems. Consider using a reference counted smart pointer instead
of a raw pointer for MyClassObj:
typedef boost::shared_ptr<BaseCls> BaseClsPtr;
MyClassObj = BaseClsPtr(new DerCls1);
It will automatically delete the object when the pointer goes out of scope
so you don't have to worry about it.You can get such a pointer at
www.boost.org
Good luck.