Dnia Sun, 18 Mar 2007 05:34:52 -0700, Wilson napisa³(a):
>>hi, i am trying to understand virtual functions, both
how to create them and how or when to use them - how they
can be used to improve a program.
sorry but im still confused as to how this should be written
Maybe try this example:
#include <iostream>
class Instrument
{
public:
//The great and famous virtual function :)
virtual void MakeSound()
{
std::cout << "Some strange noise" << std::cout;
}
//In a real-world solution, this should be declared
//as pure virtual to make this class abstract type
//[not concrete instrument].
};
//Concrete example of an instrument.
class Piano : public Instrument
{
public:
//Overriding virtual function.
void MakeSound()
{
std::cout << "Plink plank plonk" << std::endl;
}
}
class Drum : public Instrument
{
public:
void MakeSound()
{
std::cout << "Crash! Bang!" << std::endl;
}
};
class Trumpet : public Instrument
{
public:
void MakeSound()
{
std::cout << "Tra ta taa!" << std::endl;
}
}
class Musician
{
public:
void Play(Instrument* ins)
{
ins->MakeSound(); //Calling virtual function.
//This will call the overrided version
//of virtual function from the derived class.
}
}
//Let's play some funky music! :)
int main()
{
//Let we create some instruments from the free store.
//Pointers to instruments will be stored in an array.
Instrument* instruments[] = {
new Trumpet(),
new Trumpet(),
new Piano(),
new Drums()
};
Musician virtuose;
//He can play every instrument we give him:
for (int i=0; i<4; ++i) virtuose->Play(instruments[i]);
//Show's over, so let's break those instruments! :P
for (int i=0; i<4; ++i) delete instruments[i];
}
Check out the output from this program.
You should see that all instruments played by musician will
make their special beautiful sounds, and not the strange noise
from the base class ;)
--
SasQ