Virtual functions are used to implement probably the most powerful tool in C++, polymorphism. This is the idea that a pointer becomes smart enough to be capable of changing its own associated type into the type of the object that it points to at or during runtime. Virtual functions exsist in the base class and in all derived classes with some modificaiton. Here is a simple example.
Code:
#include <iostream>
using namespace std;
class Person
{
private:
int age;
float weight;
public:
Person(){age = 0; weight = 0.0;}
//Virtual functions that will be derived
//If the base class has nothing to be encapsulated
//in derived objects then these functions would
//be coded as pure virtual functions.
//virtual void getData() = 0;
virtual void getData()
{
cout << "\nENTER";
cout << "\nAGE:"; cin >> age;
cout << "\nWEIGHT:";cin >> weight;
}
virtual void showData()
{
cout << "\nAGE:" << age
<< "\nWEIGHT:" << weight;
}
};
class Student : public Person
{
private:
int sch_year;
float salary;
public:
Student(){sch_year = 0; salary = 0.0;}
//Functions with modifications
void getData()
{
Person::getData();
cout << "\nYRS IN SCHOOL:"; cin >> sch_year;
cout << "\nPAY PER HR:"; cin >> salary;
}
void showData()
{
Person::showData();
cout << "\nYEARS LEARNING:" << sch_year
<< "\nSTUDENT SALARY:" << salary;
}
};
class Teacher : public Person
{
private:
int tch_year;
float salary;
public:
Teacher(){tch_year = 0; salary = 0.0;}
//Functions with modifications
void getData()
{
Person::getData();
cout << "\nYRS TEACHING:"; cin >> tch_year;
cout << "\nSALARY PER HR:"; cin >> salary;
}
void showData()
{
Person::showData();
cout << "\nYEARS TEACHING:" << tch_year
<< "\nTEACHER SALARY:" << salary;
}
};
int main()
{
{
Student stu_obj;//Declare a derived object
Person *type; //Declare a pointer to an
//object of the base class
cout <<"\nSTUDENT DATA";
type = &stu_obj;//point that pointer somewhere else
type->getData();/*Using late binding, the compiler can now tell at runtime
what type of object the pointer is pointing to and call the
correct function for that type of object.*/
type->showData();
cout << "\n\nTEACHER DATA";
type = new Teacher; //We now point to a different type of object
type->getData(); //again, the appropriate functions are called.
type->showData();
}
return 0;
}