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

casts

Started by Sammy0037 Dec 2, 2005 at 7:14 PM 6 replies 700+ views
Original Post
Sammy0037
Sammy0037
Is using a cast a frowned upon practice? I have a function that takes a base class pointer as a parameter (common base, from which several are derived). A base pointer is used so as to allow all the derived classes to use the same function. I suppose making a temp base pointer from the derived and passing that instead would work. Cheers
SiCrane
SiCrane
Seeing as you don't need a cast to go from derived to base, I don't see a problem here. Though casts in general are a warning sign.
Sammy0037
Sammy0037
Correction.. Im not using pointers, per se, but references.

This should not work without casts. Right?

baseclass base;
derivedclass1 derived1;
derivedclass2 derived2;
derivedclass3 derived3;

DoSomething(derived1, derived2);
DoSomething(derived2, derived3);

void DoSomething(baseclass &a, baseclass &b)
{
//do something with a and b
};

////
Would an alternative way be to send derived pointers... which are received as base pointers? Does this work?

DoSomething(*derived2, *derived3);

void DoSomething(baseclass *a, baseclass *b)
{
//do something with a and b
};
RDragon1
RDragon1
Instead of typing your code into a message board and asking other people to compile it, why don't you download a compiler and see what it has to say about your code?
SiCrane
SiCrane
You don't need casts to use a derived class with a base class reference either. It should just automagically work.
Bezben
Bezben
I think generally upcasting is bad, and downcasting is fine.
RDragon1
RDragon1
You've got it backwards. Upcasting is going from Derived -> Base. Downcasting is from Base -> Derived.
Sammy0037
Sammy0037
Sorry, no I didnt post actual code. And I wasnt asking anyone to compile anything or debug. It was more of getting a general idea of what Im looking to do... to see if I am going about it the right way.

Automagic is nice, when it works... which it seems to so far now. Thanks ;o)

Topic Locked

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

Sign in to reply to this topic.