Skip to main content
GameDev.net gamedev.net
🔒 Locked

pre casting?

Started by VI2 May 6, 2004 at 3:53 AM 1 replies 250+ views
Original Post
VI2
VI2
Hey I''m wondering 2 things. I''m working with a lot of inherited objects and I was wondering 2 things. Is there a way to auto or pre cast a class so that I don''t need to cast it each time? Also is there an easy way of finding out what class type each object is? Could I put in each class, some function to return its class object so that I could use that to... do some form of automatic casting?
Drazgal
Drazgal
To precast as you put it you simply need another pointer. For example we have a parent class CParent and a child class CChild, the child can also be a parent etc so if we have

CChild Child;

and want to use it alot as a CParent make a pointer to it like so

CParent* Ptr = (CParent*)&CChild

and use Ptr to access it with recasting each time.

If you want automatic casting then have a CParent pointer inside you CChild class. In your contructor have

ParentPtr = (CParent*)this;

then use operators for the rest

operator CParent* return{ParentPtr);

then outside the class you can just do

(CParent*)Child->SomeParentMethodVersion();

or just grab the pointer

CParent* Ptr = Child;
Ptr->SomeParentMethodVersion();

Well should work I think, havent ever tried it though so give it a go, although I have a feeling the automatic casting example isnt quite what you are after. Also Im pretty sure some of my syntax is wrong, atleast for the operator line, just fix it up
psamty10
psamty10
quote:
Original post by VI2
Hey I''m wondering 2 things. I''m working with a lot of inherited objects and I was wondering 2 things. Is there a way to auto or pre cast a class so that I don''t need to cast it each time?

Also is there an easy way of finding out what class type each object is?

Could I put in each class, some function to return its class object so that I could use that to... do some form of automatic casting?


If you find yourself casting classes every time you use them, or alternatively if you need to find the exact type of an object every time, that''s usually a signal that your inheritance hierarchy is non-intuitive/poorly-designed.

The way I usually refactor my way out of this problem is to break up the inheritance hierarchy so that only objects with identical interfaces are grouped together.

If you feel like taking the easy way out, enable RTTI, and use the typeid() operator to find out the exact class type. However, I recommend you fix your class hierarchy instead...

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.