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

List the differences between method overriding and method overloading?

725


What are the 3 different types of arrays?

830


Which framework is best for desktop application?

744


What are partial classes and use of partial classes?

747


What is c# console application?

727


What do u mean by thread safe?

739


What is dataadapter c#?

682


What are access modifiers in c#?

767


Can we override interface methods in c#?

678


Is datetime value type c#?

669


Why do we need a singleton class?

757


Where do we use serialization in c#?

708


Explain lock, monitors, and mutex object in threading.

722


What is the main purpose of delegates in c#?

764


What are predicates in c#?

756