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
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
};
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.
You've got it backwards. Upcasting is going from Derived -> Base. Downcasting is from Base -> Derived.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement