Virtual Functions
If we try and run MakeSound() function:
#include<iostream>
using std::cout;
using std::endl;
class Instrument {
public:
void MakeSound(){
cout << "Instrument playing..." << endl;
}
};
class Accordion:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Accordion is playing " << endl;
}
};
class Guitar:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Slowy weeping my Guitar" << endl;
}
};
int main()
{
Instrument* i1 = new Accordion();
i1->MakeSound();
Instrument* i2 = new Guitar();
i2->MakeSound();
}
Output:
Instrument playing...
Instrument playing...
With a Virtual function, the most dervied function will be called
#include<iostream>
using std::cout;
using std::endl;
class Instrument {
public:
virtual void MakeSound(){
cout << "Instrument playing..." << endl;
}
};
class Accordion:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Accordion is playing " << endl;
}
};
class Guitar:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Slowy weeping my Guitar" << endl;
}
};
int main()
{
Instrument* i1 = new Accordion();
i1->MakeSound();
Instrument* i2 = new Guitar();
i2->MakeSound();
}
Output:
Accordion is playing
Slowy weeping my Guitar
What about Pure virtual function?
class Instrument {
public:
virtual void MakeSound() = 0;
};
Make sure all the classes have their own implementation of MakeSound(). (will have to provide it)
This Class here has became a Abstract class, because ase an abstact class has at least one pure virtual function.
#include<iostream>
using std::cout;
using std::endl;
class Instrument {
public:
virtual void MakeSound() = 0;
};
class Accordion:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Accordion is playing " << endl;
}
};
class Guitar:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Slowy weeping my Guitar" << endl;
}
};
class Piano:public Instrument {
// dervied class
public:
void MakeSound()
{
cout << "Piano Playing...." << endl;
}
};
int main()
{
Instrument* i1 = new Accordion();
Instrument* i2 = new Guitar();
Instrument* i3 = new Piano();
// We can make all the intruments play
Instrument* instruments[3]= {i1, i2, i3};
for(int i = 0; i <3; i++ )
{
instruments[i]-> MakeSound();
}
}
Output:
Accordion is playing
Slowy weeping my Guitar
Piano Playing....