Professional Documents
Culture Documents
Presented By:
Name: Farhan Ramzan
Roll No: 40901
Class: BSCS(Evening)
Submitted To: Mam Farwa
C++ VIRTUAL FUNCTION
1. Virtual function is a function in base class which is overrided in the
derived class, and which tells the compiler to perform late binding on this
function.
2. Virtual keyword is used to make a member function of the base class
virtual
HOW TO CREATE VIRTUAL FUNCTION?
1. Using virtual keyword with base class version of show function; late
binding takes place and derived of the function will be called,
because base pointer pointes an derived type of object.
2. We know that in runtime polymorphism the call to a function is
resolved at runtime depending upon the type of object.
SYNTAX
Virtual return_type function_name()
{
body
}
Ex: virtual void print()
GENDRAL FORMAT
Class class _name
{
Public:
virtual return_type function _ name (arguments)
{
Body
}
};
Class A {
};
•
EXAMPLE
• #include<iostream>
• using namespace std; • class B: public A
• class A • { private:
• { private:
• int b;
• int a;
• public:
• public:
• B()
• A()
• {
• {
• b = 2;
• a = 1;
•
• }
}
• virtual void show() • void show()
• { • {
• cout <<a; • cout <<b;
• } • }
int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}
EXAMPLE 2(with parameters)
#include<iostream>
using namespace std;
class A
class B:public A
{
{
public:
public:
virtual void show(int a,int b)
void show(int c,int d)
{
{
cout<<"the sum of"<< a << " and " << b <<
cout<<"The Multiple of"<<
" is:"<<a+b<<endl; c << " and " << d << " is:"<<c*d<<endl;
} }
}; };
int main()
{
A obj1;
B obj2;
A *ptr;
int g,h;
cout<<"enter the value of g:";
cin>>g;
cout<<"enter the value of h:";
cin>>h;
ptr=&obj1;
ptr->show( g,h);
ptr=&obj2;
ptr->show(g,h);
return 0;