I am trying to understand virtual
and pure-virtual
functions in C++. I came to know that in the derived class the virtual methods are overridden with the implementation given in the derived class.
Here is the code that i used to test this :
#include <iostream>
using namespace std;
class Base
{
protected:
int a;
public :
virtual void modify ()
{
a=200;
}
void print ()
{
cout<<a<<"\n";
}
};
class Derived : public Base
{
int b;
public :
void modify()
{
a=100;
b=10;
}
void print ()
{
cout<<a<<"\t"<<b<<"\n";
}
};
int main ()
{
Base b;
b.modify ();
b.print ();
Derived d;
d.modify ();
d.print ();
return 0;
}
Output :
200
100 10
This means that the print ()
is also overridden along with the modify ()
.
My Question :
Then why do we need virtual methods at all...?