Optimal Efficiency: dynamic_cast pointer or reference?

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
 
V

Victor Bazarov

Tomás said:
[...efficiency difference question...]

Let me ask a leading question in response: what efficiency difference
_do_ you _notice_ or _encounter_ in your application/system that prompts
you to ask this efficiency question? Hint: if you can't see any, there
is none.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top