polymorphism in oop
Polymorphism in OOP
Polymorphism is a crucial aspect of object-oriented programming, where a member function with the same name is defined in both base and derived classes.
Polymorphism refers to the ability of objects from different classes, connected through inheritance, to respond differently to the same function call.
Polymorphism is facilitated through the use of virtual functions. This capability arises from the fact that a pointer to a base class object can also point to any object of its derived class.
Virtual Functions
Virtual means existing in appearance but not in reality. When virtual functions are employed, a program that invokes a function from one class actually invokes a function from a different class.
Normal Member Functions Accessed with Pointers
Our initial example explores the scenario where a base class and its derived classes define functions with identical names. Certain behaviors arise when you access these functions using pointers but without utilizing virtual functions.
Virtual Member Functions Accessed with Pointers
Now, we’ll modify our program by adding the virtual keyword before the declaration of the show() function in the base class.
Late Binding
Late binding refers to the process of resolving the function call at runtime. When a function call is made through a base class pointer or reference to a derived class object, late binding ensures that the appropriate function implementation from the derived class is called, based on the type of the object being referred to.
Abstract Classes and Pure Virtual Functions
A class that consists of at least one pure virtual function, and When we will never want to instantiate objects of a base class, we call it an abstract class. Such a class exists only to act as a parent of derived classes that will be used to instantiate objects. It may also provide an interface for the class hierarchy. It's like a documentation of classes.
but how to create an abstract class.
By placing at least one pure virtual function in the base class.
A pure virtual function has the expression =0 added to the declaration.
Post a Comment