virtual functions | polymorphism | oop

5
VIRTUAL FUNCTIONS - Firoj Ghimire - Shubham Ghimire - Suyash Nepal

Upload: shubham-ghimire

Post on 23-Jan-2018

240 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Virtual Functions | Polymorphism | OOP

VIRTUAL FUNCTIONS- Firoj Ghimire

- Shubham Ghimire

- Suyash Nepal

Page 2: Virtual Functions | Polymorphism | OOP

What is Virtual function ?

• A virtual function is a member function that is declared within a base class and redefined by a derived class.

• To create virtual function, precede the function’s declaration in the base class with the keyword virtual.

• When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.

• A virtual function uses a single pointer to base class pointer to refer to derive all the objects.

• Virtual functions belongs to the branch of Runtime Polymorphism in C++

Page 3: Virtual Functions | Polymorphism | OOP

Syntax

Page 4: Virtual Functions | Polymorphism | OOP

How virtual function works ?

• 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 base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime polymorphism.

Page 5: Virtual Functions | Polymorphism | OOP

Pure Virtual Function

• Virtual function without function body is pure virtual function.

Syntax

virtual int area()=0 //pure virtual function