Re: Classes from pointers?
From: Cy Edmunds (cedmunds_at_spamless.rochester.rr.com)
Date: 10/12/03
- Next message: Willie Clement: "new"
- Previous message: Moonlit: "Re: Newbie Q: returning objects from the freestore"
- In reply to: zRaze: "Classes from pointers?"
- Next in thread: zRaze: "Re: Classes from pointers?"
- Reply: zRaze: "Re: Classes from pointers?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 12 Oct 2003 02:47:54 GMT
"zRaze" <abuse@msn.com> wrote in message
news:o2agov8svcpv69oah2mus8ebka1v1fq0sl@4ax.com...
> 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.
-- Cy http://home.rochester.rr.com/cyhome/
- Next message: Willie Clement: "new"
- Previous message: Moonlit: "Re: Newbie Q: returning objects from the freestore"
- In reply to: zRaze: "Classes from pointers?"
- Next in thread: zRaze: "Re: Classes from pointers?"
- Reply: zRaze: "Re: Classes from pointers?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|