About Virtual functions and their use ?

Answer Posted / sandeep

Virtual keyword is used to perform the dynamic binding
instead of early binding. To be brief below is the example

Class base
{
void display()
{
cout<<"in Base";
}
}
Class derived: public base
{
void display()
{
cout<<"in derived";
}
}
void main()
{
base* ptr;

ptr = new derived;
ptr->display();
}

When we execute above program output will be displayed as
"in base", but expected output was "in derived". So compiler
was choosing member function which matches the type of the
pointer rather than the member function which matches the
content of the pointer. But when we use Virtual keyword in
base class, it perform the dynamic binding, i.e., at run
time it choose the function to execute and executes "in
derived". So when we use virtual keyword, compiler will
select the member function which matches the content of the
pointer and it will ignore the member function which matches
the type of the pointer.

Is This Answer Correct ?    17 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the use of oops in c#?

500


What is the difference between string keyword and system.string class?

511


What is poco c#?

476


Explain the constructor in c#.

558


What is difference between dictionary and hashtable?

510






What issues can be faced while delivering code?

1469


Can hashtable have duplicate keys in c#?

471


Is exe is machine dependent?

490


Explain the difference between the debug class and trace class?

492


What is dll in vb.net?

480


Explain About friend and Protected friend

515


Describe the process of “exception handling implementation” in c#?

509


What are the advantages of clr procedure over t-sql procedure?

581


Why is it not a good idea to use empty destructors?

537


Is c# a backend language?

561