top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Can someone explain C++ Virtual Methods?

+2 votes
233 views
Can someone explain C++ Virtual Methods?
posted Aug 13, 2014 by Khusboo

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote
 
Best answer

Virtual function in C++ are the case where base class and derived class has same function - In this case if your access the function using pointer of base class then, the function in the base class is executed even if, the object of derived class is referenced with that pointer variable.

Check the following code

#include <iostream>
using namespace std;
class A
{
    public:
       void display()
         { cout<<"I am inside base class.\n"; }
};

class B : public A
{
    public:
       void display()
         { cout<<"I am inside of derived class.\n"; }
};

int main()
{
    A *a;
    B b;
    a->display();

    a = &b;   
    b->display(); // Here a is referring to derived class but still base class function would be called 
}

Output

I am inside base class.
I am inside base class.
answer Aug 13, 2014 by Salil Agrawal
+1 vote

Actually, it is the concept of run-time polymorphism. As it is very nicely described by the Salil Agrawal sir in his answer that if we call a derived class function, which is overridden in the derived class using the base class pointer it does not call the derived class function. It simply call the base class function.

In order to resolve this problem we use the virtual keyword before the function in base class. It is optional to prefix virtual keyword in derived class. when we make any function virtual in a class a virtual table get created corresponding to each which is derived from the base class. this table is known as vtable, which contains the function pointer. which is pointed by a pointer known as vptr, which is stored in the few bytes of the object. Therefore when we assign the address of derived class object to base class pointer, it calls the derived class function.

plz comment and correct me if i understand wrongly.

answer Aug 14, 2014 by Prakash Singh
...