T
Tomás
dynamic_cast can be used to obtain a pointer or to obtain a reference.
If the pointer form fails, then you're left with a null pointer.
If the reference form fails, then an exception is thrown.
Would "Feed1" or "Feed2" be preferable in the following:
#include <iostream>
#include <typeinfo>
using std::bad_cast;
using std::cout;
using std::endl;
class Mammal
{
public:
Mammal()
{
cout << "Constructor: Mammal" << endl;
}
virtual ~Mammal()
{
cout << "Destructor: Mammal" << endl;
}
/************************************
Virtual destructor because Mammal
has to be polymorphic.
************************************/
};
class Panda : public Mammal {
public:
Panda()
{
cout << "Constructor: Panda" << endl;
}
~Panda()
{
cout << "Destructor: Panda" << endl;
}
};
void TellZooKeeperThatWeFedAPanda()
{
cout << "Hey Zoo Keeper, we just fed a Panda." << endl;
}
void Feed1(Mammal &mammal)
{
if ( dynamic_cast< Panda* > ( &mammal ) )
{
TellZooKeeperThatWeFedAPanda();
}
}
void Feed2(Mammal &mammal)
{
try
{
dynamic_cast< Panda& > (mammal);
TellZooKeeperThatWeFedAPanda();
}
catch ( bad_cast ) { }
}
int main()
{
Mammal panda;
Feed1( panda );
Feed2( panda );
}
-Tomás
If the pointer form fails, then you're left with a null pointer.
If the reference form fails, then an exception is thrown.
Would "Feed1" or "Feed2" be preferable in the following:
#include <iostream>
#include <typeinfo>
using std::bad_cast;
using std::cout;
using std::endl;
class Mammal
{
public:
Mammal()
{
cout << "Constructor: Mammal" << endl;
}
virtual ~Mammal()
{
cout << "Destructor: Mammal" << endl;
}
/************************************
Virtual destructor because Mammal
has to be polymorphic.
************************************/
};
class Panda : public Mammal {
public:
Panda()
{
cout << "Constructor: Panda" << endl;
}
~Panda()
{
cout << "Destructor: Panda" << endl;
}
};
void TellZooKeeperThatWeFedAPanda()
{
cout << "Hey Zoo Keeper, we just fed a Panda." << endl;
}
void Feed1(Mammal &mammal)
{
if ( dynamic_cast< Panda* > ( &mammal ) )
{
TellZooKeeperThatWeFedAPanda();
}
}
void Feed2(Mammal &mammal)
{
try
{
dynamic_cast< Panda& > (mammal);
TellZooKeeperThatWeFedAPanda();
}
catch ( bad_cast ) { }
}
int main()
{
Mammal panda;
Feed1( panda );
Feed2( panda );
}
-Tomás