×

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

C Program of Fencing the Ground

The college's ground is rectangular. Fencing the ground the management makes the decision to construct a fence around the ground. They planned to wrap a thick rope around the ground...

1 minute read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Explain the two-way selection in C

In C programming, a two-way selection statement is used to choose between two different options based on a Boolean expression. The two-way selection statement in C is the if statement. The...

6 minutes read.

Flow Chart of Do while loop in C

This is a flowchart that represents the process of executing the Do while loop in the C programming language Generally, as we know there are three main components of Do While...

3 minutes read.

How to install a C compiler in windows 10-64bit

Many C compilers can be installed on your pc. The most downloaded compilers include GCC, Turbo C++, Visual Studio, etc. This article includes the installation of the Turbo C++ compiler in...

6 minutes read.

fopen() function in C

fopen() function, is one of the file handling functions. It is used to open the existing file and perform operations on the file. If the file does not exist, it...

3 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

C Decision control statement

Decision Making C conditional statements are used to specify one or more conditions. The statements will be executed if the condition becomes true otherwise alternative statement will be executed if the...

3 minutes read.

#error #pragma in C

#error, #pragma in C #error, also known as the error directive in the C language. It will not allow you to make any compilation fail and immediately issues a statement which...

4 minutes read.

What is a buffer in C?

A buffer is an area of memory set aside for the temporary storage of data. A data buffer (or just buffer) is a region of a physical memory storage used to...

5 minutes read.

Enumeration (Enum) in C

Enumeration (Enum) in C: In the C programming language, the enum is referred to as an enumerated type. Enum is a user defined data type consisting of integer values and...

3 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

C Data type

Data Types in C with Examples Data types are used to define the type of data that a variable can store to perform a specific operation.ANSI C provides three types of...

2 minutes read.

Limitations of Synchronisation and Uses of Static Synchronisation in Multithreading

The multithreading component of java is the element around which the idea rotates as it permits simultaneous execution of at least two program pieces for the most significant usage of...

9 minutes read.

Dynamic memory allocation

Dynamic memory allocation is used to allocate the memory at runtime. It has following function within <stdlib.h> header file. Function Syntax malloc() malloc (number *sizeof(int)); calloc() calloc (number, sizeof(int)); realloc() realloc (pointer_name, number * sizeof(int)); free() free (pointer_name); malloc() function The process...

2 minutes read.

Self-referential structure in C

Self-referential structure in C A self-referential structure is a structure that can have members which point to a structure variable of the same type. They can have one or more pointers...

3 minutes read.

fork() in C

Introduction To create a new function in the system, there is a need for a system call, i.e. fork system call. It is also known as the child process. These child...

2 minutes read.

Assignment Operator Program in C

An assignment operator is a symbol used to assign a value to a variable in a programming language. The assignment operator is often the equal symbol (=) in programming languages....

12 minutes read.

Else If Ladder in C

What is Else If Ladder: When there are multiple options and a user has to decide from the options, we use Else If Ladder. Basically, it is an extension of if...

3 minutes read.

Continue in C

C language: C language is a procedure oriented programming language. We can say that it is a platform dependent language. C language is introduced by Dennis Ritchie in the year 1970. We...

2 minutes read.