Link to home
Start Free TrialLog in
Avatar of prain
prainFlag for United States of America

asked on

C++ : Casting from Template to a Base Class pointer... How?

Here is a way I set up my design

class Master is a "interface".....

class Master{

      ~Master(){}

      virtual void setSomeThing(int aValue) = 0;
};

Class Slave is a template derived from Master.......

template <class PositionType, int Positionize>
class Slave : public Master
{
   Slave (std::string name, bool someValue)
   {
   }

   /* Overrides....*/
   void setSomeThing(int aValue) {/** Do sometthing here **/}
}

Note : PositionType is designed to take any enum type.

So in a main() I do the following...

main()
{

 Master* aMaster = new Slave <SomeType, someSize>("aName" ,false);
                                          /** SomeType is a enum type **/
 /** The above instantiation compiles and work good...**/
 
 //And then  I want the above object back to a Salve pointer....
 //So I try this,...
 
 Slave <SomeType, someSize>* convertback = (Slave <SomeType, someSize>) aMaster;
//Cannot do this. error.

}

So my question is.. how to cast the Master pointer (which is pointing to a Slave object) back to a Slave pointer?
ASKER CERTIFIED SOLUTION
Avatar of TommySzalapski
TommySzalapski
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of prain

ASKER

Oh! shoot. How come I did not see that. Thank you!
Avatar of pepr
pepr

Beware of the explicit cast that you are using. It came from C and using it, you give up some compile-time error detection. You should prefer

    static_cast <new_type> (expression)

or
   
    reinterpret_cast <new_type> (expression)