By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,183 Members | 1,190 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,183 IT Pros & Developers. It's quick & easy.

Optimal Efficiency: dynamic_cast pointer or reference?

P: n/a

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
Feb 24 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Tomás wrote:
[...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
--
Please remove capital As from my address when replying by mail
Feb 24 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.