virtual function

VENNILAV6 1,636 views 10 slides Nov 06, 2019
Slide 1
Slide 1 of 10
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10

About This Presentation

virtual function with example program


Slide Content

VIRTUAL FUNCTION PRESENTED BY Ms . V.VENNILA., MCA., M.Phil ., Asst.Prof of Information Technology, Bon Secours College for Women, Thanjavur

C++ VIRTUAL FUNCTION 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. Virtual keyword is used to make a member function of the base class virtual,

VIRTUAL FUNCTION A virtual function is a member function that is declared as virtual within a base class and redefined by a deriver class. To create virtual function, precede the base version of function’s declare with the keyword virtual. The method name and type signature should be same for both base and derived version of function.

Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using function base class pointer , it can be achieved by defining the function as virtual in base class, this is how virtual function supports runtime polymorphism . HOW VIRTUAL FUNCTION WORKS?

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. We know that in runtime polymorphism the call to a function is resolved at runtime depending upon the type of object . USING VIRTUAL KEYWORD

Virtual return _ type function _ name ( ) { …… …… …… } Ex: virtual void print( ) SYNTAX

Class class _ name { Public: virtual return _ type function _ name (arguments) { …. ….. } }; Class A { GENDRAL FORMAT

Virtual function belongs to the branch of runtime polymorphism in c++ polymorphism Compile time/early binding Run time/late binding Function overloading Operator overloading VIRTUAL function/function overloading

#include< iostream.h > Class base { Public: Virtual void print ( ) { Cout<<“print base class”; } Void show ( ) { Cout<<“show base class”; } }; Class derived : public base { Public: Void print ( ) { Cout<<“print derived class”; } Void show ( ) EXAMPLE

{ cout <<“show derived class”; }}; int main ( ) { base*bptr; bptr =d; derived d; bptr print( ); bptr show( ); } OUTPUT Print derived class Show base class