Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are only virtual methods overridden [duplicate]

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

like image 475
Rohith R Avatar asked Oct 23 '25 19:10

Rohith R


1 Answers

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.

like image 190
selbie Avatar answered Oct 26 '25 09:10

selbie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!