×

Run Time Polymorphism in C

What is polymorphism?

Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. An individual who can have multiple traits at once is a real-world example of polymorphism. Being a father, a spouse, and an employee all at once makes one feel like a man. As a result, the same person behaves differently depending on the circumstance. Polymorphism is the term for this. One of the key components of Object-Oriented Programming is polymorphism.

Types of polymorphism

  1. Compile time polymorphism
  2. Run time polymorphism

Does c support polymorphism?

Generally, polymorphism is not supported by the C language. A characteristic of object-oriented programming (OOP) languages is polymorphism. Polymorphism is only supported by object-oriented languages. Because OOP is not a concept in C programming, polymorphism is also not a concept in C programming.

Although C doesn't naturally support polymorphism, there are design patterns that can simulate dynamic dispatch by leveraging function pointers, base 'class' (structure) casts, etc. A nice illustration is the GTK library.

Run time polymorphism in c

A binding method that can decide which function should be called at runtime based on the object type making the call would be preferable to the static binding.

Since the suitable function is chosen dynamically during runtime, this sort of binding is often referred to the as late or dynamic binding.

Oops (polymorphism) is a programming technique, not a language characteristic. Following this, you may use C to implement inheritance and polymorphism. Therefore, while C lacks classes, it does contain structures. By first establishing an instance of the base structure in the derived structure, we can create two structures and call a method from one to the other. This is simply inheritance: convert the derived struct instance to the base class (upcasting), utilize the base class's methods, or access data members. Using a function pointer, we may implement polymorphism in the same way.

Use of run time polymorphism

In order to interact with any class descended from that base without being aware of or caring about the precise type, it is necessary to design a common base class (typically one that just specifies an abstract interface). So you may create a function called furtle(A&) that works with class A, class B, or any other class descended from class A. Regardless of the actual class type, it can call the virtual functions that are overridden to do the proper action.

Even so, we can use the Add() method of Class B directly using either its object or its pointer.

Example programs in c using run-time polymorphism

So is possible even though the language does not give you as many tools to achieve it as OO-based languages do.

 For instance:

Example 1

#include <stdio.h>
#include <stdlib.h>


typedef struct { 
    void (*eat)(); 
    void (*say_something)(); 
} Animal; 


void dog_eat() 
{ 
puts("I eat cats"); 
} 


void dog_say_something() 
{ 
    puts("Gau"); 
} 


void cat_eat() 
{ 
puts("I eat mice"); 
} 


void cat_say_something() 
{ 
    puts("Meow"); 
} 


Animal* new_dog() 
{ 
    Animal* a = malloc(sizeof(Animal)); 
    a->eat = dog_eat; 
    a->say_something = dog_say_something; 
    return a; 
} 


Animal* new_cat() 
{ 
    Animal* a = malloc(sizeof(Animal)); 
    a->eat = cat_eat; 
    a->say_something = cat_say_something; 
    return a; 
} 


void do_something(const Animal* a) 
{ 
    a->eat(); 
    a->say_something(); 
} 


int main() 
{ 
    Animal* a = new_cat(); 
    Animal* b = new_dog(); 


do_something(a); 
puts("*********"); 
do_something(b); 


    free(a); 
    free(b); 


    return 0; 
}

Output

I eat mice
Meow
*********
I eat cats
Gau

Example 2

#include <stdio.h>
#include <stdlib.h>
 struct foo; 
typedef void(*member_function_t)(struct foo*); 
typedef struct foo 
{ 
	member_function_t bar; 
	void *data; 
} foo; 


void bar_impl_1(foo *this) 
{ 
    //
} 


void bar_impl_2(foo *this) 
{ 
	//  
} 


int main() 
{ 
	foo f1 = {bar_impl_1}; 
	foo f2 = {bar_impl_2}; 


	f1.bar(&f1); // Equivalent to bar_impl_1(&f1) 
	f2.bar(&f2); // Equivalent to bar_impl_2(&f2) 
}

Advantages of run time polymorphism in c

  • The ability to reuse codes, i.e., classes that have already been created, tested, and implemented, is helpful to programmers. greatly reduces time.
  • Multiple data kinds can be stored in a single variable.
  • The code is simple to debug.

Conclusion

Method overriding is used to implement runtime polymorphism. When we call the methods with their appropriate objects, everything goes smoothly. However, unexpected outcomes happen from static linking when we have a base class pointer and we call overridden methods using the base class pointer pointing to the derived class objects. We employ the idea of virtual function to get around this.


Related Topics

Union Program in C

 How should a union be defined?  In C programming, a Union is a method used to organize different data types into groups in the same way that Structures are used. We...

4 minutes read.

C program to Store Information of Students Using Structure

What is the Structure in C? User-defined data types include structures. Structures aid your ability to combine things of various categories into a single group. Like arrays, it operates similarly. A...

3 minutes read.

Merge Sort in C

The merge sort follows the principle of the divide and conquers algorithm. Firstly it divides the input of an array into two halves and then calls itself for the two...

4 minutes read.

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

Types of Pointers in C

Pointers in C A pointer is a variable and this variable contains the address of another variable, i.e it’s a variable which has the address of another variable as its value....

4 minutes read.

Loop Statement in C

Loop statement is used to execute one or more statement repeatedly multiple times. There are three types of loops in C language. Why use loop? We can use loop because it executes a...

2 minutes read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

Selection sort in C

In the C standard, the selection sorting technique exists where the smallest among the unsorted elements of the array is selected at each time and is then inserted into its...

3 minutes read.

Runtime vs compile time in C

In the C programming language, the often used terms in every step consist of compile time and runtime. The compile time is referred to the source code that will be...

4 minutes read.

Pure Virtual Function in C

Before knowing about the pure virtual function some of the important points about the virtual function in C++ are given below. In c++ the member function that is defined in the...

4 minutes read.

Types Of Structures In C

We can normally store elements of the same datatype with the help of an array in C programming. We can store multiple numbers of elements of a character data type...

3 minutes read.

Variable in C

Variable is an identifier that holds data in memory. It is used to identify input data in a program. The value of the variable can change at the time of...

2 minutes read.

Write() function in c

As the name suggests the write () function is used to write the file descriptor. In other words it is used to write any file name without specifying file name,...

3 minutes read.

Find Day from Day in C Without using function

Introduction: In the given article, I find daily in C without using functions. It takes 365 days for the earth to revolve around the sun. It will be close to...

3 minutes read.

Compound Interest Program in C

Interest on loans and deposits is compound interest. This is the most commonly used concept in everyday life. Compound interest on an amount is based on principal and interest earned...

3 minutes read.

Difference between C and Java

C programming and Java programming are two of the earliest programming languages. C programming follows a procedural approach whereas Java programming follows an object-oriented approach. Java programming is a part...

3 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Functions in C

What is function? Functions are defined as the set of announcements which take inputs, perform operations and provide results. The operation of a function only performs when the function gets called....

4 minutes read.

Variable Declaration in C

What is a Variable? A Variable is nothing more than a name for a memory place where data/information can be stored. Any alphabet (from a to z or A to Z), the...

4 minutes read.

Example of Iteration in C

The iterations in the C language are the statements which are executed number of times until a certain condition is reached. These iterations are regarded as “Loops” in C language....

3 minutes read.