A virtual function in a C++ class simply indicates to the compiler that sub-classes of the current class may override that function.
in such a case the compiler ranages to call the overridden function rather than the base cass function if a base class pointer is used.
Consider this program
-
#include "stdio.h"
-
#include "stdlib.h"
-
-
class A
-
{
-
public:
-
A(){};
-
void print(){puts("class A");};
-
};
-
-
-
class B : public A
-
{
-
public:
-
B(){};
-
void print(){puts("class B");};
-
};
-
-
int main(int argc, char* argv[])
-
{
-
B b;
-
A *pA = &b;
-
-
pA->print();
-
b.print();
-
-
return EXIT_SUCCESS;
-
}
-
The output is
class A
class B
Even though pA points to a class of type B it still calls the print function in class A, however if class A is changed to
-
class A
-
{
-
public:
-
A(){};
-
virtual void print(){puts("class A");};
-
};
-
the the program now outputs
class B
class B
because the print function is declared virtual the compiler knows that sub-classes may override that function so when it access the instance of the class through the pointer it will check and if the function is overridden it will call the function from the sub-class.
You can also have pure virtual functions, if print is a pure vrtual function then class A becomes
-
class A
-
{
-
public:
-
A(){};
-
virtual void print() = NULL;
-
};
-
class A is now an abstract function, that is you can no longer declare an instance of class A because it has no implementation of print. This tells the compiler that the is a class of general type A but that it will be sub-classed and the pure virtual functions will be over-ridden in order to be used.
A class that sub-classes from an abstract class (class B in this instance) must override all the pure-virtual functions in the base class or be an anstract class itself.