-
virtual methods
// Listing 14.2 Using dynamic_cast.
// Using rtti
you can ignore this post, please read the next one, where I made the question more understadable
Code:
#include <iostream>
using namespace std;
enum TYPE { HORSE, PEGASUS };
class Horse
{
public:
virtual void Gallop(){ cout << "Galloping...\n"; } //why make this one
private:
int itsAge;
};
class Pegasus : public Horse
{
public:
virtual void Fly() {cout<<"I can fly! I can fly! I can fly!\n";//and
//this here virtual methods?
};
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]);
if (pPeg)
pPeg->Fly();
else
cout << "Just a horse\n";
delete Ranch[i];
}
int x; cin>>x;
return 0;
}
-
Correct me if I am wrong, but I have a question. When you make two virtual methods with the same name on two different classes then depending on the object forwhich you're calling the virtual method for is going to be called, the correct one is called?
Code:
ex.
class Pegasus : public Horse
{
public:
virtual void Fly() {cout<<"I can fly! I can fly! I can fly!\n";}
class Horse
{
public:
void Gallop(){ cout << "Galloping...\n"; }
virtual void Fly() { cout << "Horses can't fly.\n" ; }
If I were to make a horse object....and would called on the virtual method Fly(), I would get "Horses can't fly", or if I were to make a Pegasus object and calle don the Virtual Fly() method, I would get "I can fly......."?
-
Correct me if I'm wrong, but aren't there
-
[sarcasm]
oh Good one Brian, too bad that doesn't answer my question.
[/sarcasm]
Damn they need to make sarcasm tags!!!!!!!!!!!
-
Does that make you happy?
-
can't really understand your question but i'll try anyways.
if it was a pegasus, the method in pegasus would be called.
if it was a horse, the method in horse would be called.
if you had a horse pointer pointing to a pegasus, the method in pegasus would be called.
-
Yeah that's it thank you.
-