Your first version was correct. No need to use cast operators, the cast from derived to base class is absolutely legal. In the opposite case if you want to cast from base to derived type, you can use either static_cast or dynamic_cast. The difference is dynamic_cast guarantees safe casting and if something is wrong it returns a NULL pointer, and static_cast performs no any checks before casting, and can bring to runtime errors. Note, that dynamic_cast can be used for classes containing virtual function table, i.e. you should have at least one virtual function in base class.
class Base {
...........
private:
virtualvoid f();
};
class Derived1 : public Base {
...........
public:
void func1();
};
class Derived2 : public Base {
...........
public:
void func2();
};
// global function
void exec(Base * pb)
{
Derived *pd = dynamic_cast<Derived1>(pb);
if (0 != pd) { // here you exactly know that the argument
// was of Derived1 type, and can call its member
pd->func1();
} else { // pb is of Derived2 type
pd = static_cast<Derived2>(pb);
pd->func2();
}
}