-
Using rtti (help!!!!!!!)
Code:
// Listing 14.2 Using dynamic_cast.
// Using rtti
#include <iostream>
using namespace std;
enum TYPE { HORSE, PEGASUS };//doesn't seem to be really needed for this
//project to run, but oh well, That's Jesse Liberty for you right there.
class Horse
{
public:
virtual void Gallop(){ cout << "Galloping...\n"; }
private:
int itsAge;
};
class Pegasus : public Horse
{
public:
virtual void Fly() {cout<<"I can fly! I can fly! I can fly!\n";}
};
const int NumberHorses = 5;
int main()
{
Horse* Ranch[NumberHorses];
Horse* pHorse;
int choice,i;
for (i=0; i<NumberHorses; i++)
{
cout << "(1)Horse (2)Pegasus: ";
cin >> choice;
if (choice == 2)
pHorse = new Pegasus;
else
pHorse = new Horse;
Ranch[i] = pHorse;
}
cout << "\n";
for (i=0; i<NumberHorses; i++)
{
Pegasus *pPeg = dynamic_cast< Pegasus *> (Ranch[i]);
/* What is this saying here?*/
if (pPeg)// what is this saying here?
/* is it asking to say "if pReg= dynamic_cast< Pegasus *> (Ranch[i])
then call the fly method or what?*/
pPeg->Fly();
else
cout << "Just a horse\n";
delete Ranch[i];
}
int x; cin>>x;
return 0;
}
/* Thank you all in advance for you help *
-
>/* is it asking to say "if pReg= dynamic_cast< Pegasus *> (Ranch[i]) then call the fly method or what?*/
Yes, if Ranch[i] is a Pegasus the cast will be valid otherwise it will fail and pReg will point to NULL (if Ranch[i] is only a Horse).
-
oh thanks that was easy, glad to know I was on the right track.
take this for example
Pegasus *pPeg = dynamic_cast< Pegasus *> (Ranch[i]);
could you tell me the syntax for this..........because like this dynamic_cast< Pegasus *> I don't really know what this is exactly doing if I had to use some other time.
-
>could you tell me the syntax for this
It's the C++ casting syntax.