I am not able to understand the concept of virtual functions. When a member function of base class is redefined in derived class,the redefined function can be used to get desired output. Then why there is a need to use virtual functions? For instance, the following two codes produce the same output.
Code 1:
#include<iostream>
using namespace std;
class Window
{
public:
virtual void Create()
{
cout <<"Base class Window\n"; }
};
class CommandButton : public Window
{
public:
void Create()
{
cout<<"Derived class Command Button - Overridden C++ virtual function\n"; }
};
int main()
{
Window *x, *y;
x = new Window();
x->Create();
y = new CommandButton();
y->Create();
}
Code 2:
#include<iostream>
using namespace std;
class Window
{
public:
void Create()
{
cout <<"Base class Window\n"; }
};
class CommandButton : public Window
{
public:
void Create()
{
cout<<"Derived class Command Button - Overridden C++ virtual function\n"; }
};
int main()
{
Window *x;
CommandButton *y;
x->Create();
y->Create();
}
In code 2 I have not used virtual function. When the mere redefining of function could achieve desired goal why virtual functions are used?