Professional Documents
Culture Documents
Virtual Functions and Polymorphism
Virtual Functions and Polymorphism
• Advanced concepts
• Normal member functions accessed with pointers
• Virtual member functions accessed with pointers
• Virtual functions
– Define
– Why
– Polymorphism
– Conditions to be polymorphic
• Late binding
• Static binding
• Abstract classes and pure virtual functions
Virtual Functions and Polymorphism
• Example: person class hierarchy
• Virtual destructors~
• Virtual base classes
• Friend Functions
• Friend classes
• Static functions
• ‘this’ --🡪 pointer
Normal member functions access with pointers: Predict
output
Virtual Functions accessed with pointers
Virtual Functions and Polymorphism
• Virtual means existing in appearance but not in reality.
• Programmatically
– When virtual functions are used, a program that appears to
be calling a function of one class may in reality be calling a
function of a different class
• Why are virtual functions needed?
– Suppose, you have a number of objects of different classes
but you want to put them all in an array and perform
particular operation on them using the same function call
– Ex: Sahpes-> triangle, square, circle etc.,
– Each of these classes has a member function draw() that
causes the object to be drawn on the screen
Virtual Functions and Polymorphism
Array draw()
Shape
}
Note: additional concept
abstract classes enforces polymorphism
Abstract class
Points to remember: abstract class
• =0, is syntax to tell the compiler the function is pure virtual
• If the class consists of at-least one virtual function, that
class is called abstract class
• The abstract class can’t be instantiated
• The class which inherits abstract class , it has to override
the all the virtual functions of the base class otherwise,
that class also become abstract class.
• The abstract class provides interface for the class hierarchy
• A document makes note of abstract classes in a class
hierarchy, to help some who uses your class hierarchy as a
library
Virtual Functions and Person class hierarchy
• Person:
– Data member: name
– Functions: getName(), putName(), getData(), isOutstanding()