3

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...?

Rohith R
  • 1,309
  • 2
  • 17
  • 36
  • "This means that the print () is also overridden along with the modify ()." No, it does not mean this. In the second case a `Derived` instance was used to call the `print` function and that's what happened. – James Adkison Oct 25 '15 at 05:55
  • @JamesAdkison actually, yes it does mean it's overridden. the method invoked is the overridden method, for the actual object type. what virtual is for, is so all virtual versions (because "it's virtually the same object") will call the overridden, no matter which object type it's cast as. they're giving you the additional language power to choose which you want kept overridden when cast as different types. that's the true power of Polymorphism. – Puddle Jun 14 '18 at 14:05
  • @Puddle The `Derived::print` function is non-virtual and it shadows the `Base::print` function, it does not `override` it. – James Adkison Jun 14 '18 at 16:43
  • @JamesAdkison it literally overrides methods. whether it's Polymorphic or not is a separate concept. but of course, based on the technical term for none-Polymorphic overridden methods, you are correct that it's called shadowed. but in global intelligent perception of understanding, it's still just another way of saying, overridden, but not Polymorphic. lol – Puddle Jun 14 '18 at 23:55
  • Polymorphism - the ability to appear in many forms – Puddle Jun 14 '18 at 23:55

1 Answers1

3

Consider this case with your code sample:

Base* b = new Derived();
b->modify();
b->print();

Even though b points to an instance of Derived, the invocation of virtual method b->modify would correctly call Derived::modify. But the invocation of b->print, which is not declared virtual, would print 200\n without the leading \t char as you have in Derived::print.

selbie
  • 100,020
  • 15
  • 103
  • 173