T
The Directive
I can't understand why in this folling example the message
"Base.Draw()" is printed. Shouldn't "Derive.Draw" be printed because
of polymorphism? How can I rewrite this example using a vector to
achieve polymorphism. Help!!! I'm very confused.
//Base class.
class Base
{
public:
Base()
{}
virtual void Draw()
{
cout << "Base.Draw()\n";
}
};
//Derive class.
class Derive: public Base
{
public:
Derive()
{
}
void Draw()
{
cout << "Derive.Draw()\n";
}
};
//Define the name space to use.
using namespace std;
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp;
//Add derive object.
Derive d1;
temp.push_back( d1 );
//Add another derive object.
Derive d2;
temp.push_back( d2 );
//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x].Draw();
}
//Pause the DOS command window.
system("PAUSE");
//Return system status.
return 0;
}
"Base.Draw()" is printed. Shouldn't "Derive.Draw" be printed because
of polymorphism? How can I rewrite this example using a vector to
achieve polymorphism. Help!!! I'm very confused.
//Base class.
class Base
{
public:
Base()
{}
virtual void Draw()
{
cout << "Base.Draw()\n";
}
};
//Derive class.
class Derive: public Base
{
public:
Derive()
{
}
void Draw()
{
cout << "Derive.Draw()\n";
}
};
//Define the name space to use.
using namespace std;
//Main method. C++ program beings execution here.
int main(int argc, char *argv[])
{
vector<Base> temp;
//Add derive object.
Derive d1;
temp.push_back( d1 );
//Add another derive object.
Derive d2;
temp.push_back( d2 );
//Loop through the vector.
for (int x=0; x < temp.size(); x++)
{
temp[x].Draw();
}
//Pause the DOS command window.
system("PAUSE");
//Return system status.
return 0;
}