casts

Started by
6 comments, last by Sammy0037 18 years, 4 months ago
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
Advertisement
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.
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
};
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?
You don't need casts to use a derived class with a base class reference either. It should just automagically work.
I think generally upcasting is bad, and downcasting is fine.
You've got it backwards. Upcasting is going from Derived -> Base. Downcasting is from Base -> Derived.
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)

This topic is closed to new replies.

Advertisement