Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / C++
Article

Polymorphism in C

Rate me:
Please Sign up or sign in to vote.
2.52/5 (10 votes)
10 Feb 20073 min read 52.9K   349   25   9
This articles covers some technics about building object oriented aspects in structural languages

Overview

Introduction

With the change of solution methods of real-life problems and designed architectures, software projects started to be developed using object oriented programming instead of structural programming. Powerful structural languages such as C has become less popular in large scale projects due to difficulties of adapting structural solutions for maturity factors(reusability, extendibility etc...) .We discuss adaptation of an OOP concept polymorphism to structural languages.

Background

Due to OOP is completely a different approach according to Structural programming, it comes with many programming technics different than Structural programming. One of these technics is polymorphism. Polymorphism simply means "common interface, specific implementation", deeply means each class has its own implementation while they share a common interface. This concept brings benefits to object oriented programming such as combining all objects behaviours in a standard interface and applying it with all classes. As an OOP concept, can this feature be implemented in a structural language such as C? C provides powerful programming abilities like pointers and structures. And by using these elements, polymorphism model can be partially implemented.

Using the code

This code is only a sample for what you can do in C, in polymorphism manner. So code is small and to explain how it works, lots of comments has been added. Also other tips are given how you can make structural concept similar to object oriented.

First we should have a structure that acts like class and related functions

C++
#ifndef _POLY_STRUC_H
#define _POLY_STRUC_H

struct POLY_STRUCT
{
    /* Extra Fields and Encapsulation functions here */
        
    void (*poly)( );    // Polymorphic method 
                        // init to null to this method 
                        // to abstract 
                        // so making this struct an 
                        // abstract class
    };

    /* Allocates and initializes a POLY_STRUCT with a 
       function pointer */
    struct POLY_STRUCT *InitPoly( void (*poly)() );
        
    /* Deallocates a POLY_STRUCT */
    void DestroyPoly( struct POLY_STRUCT *poly );
        
    /* Executes run function of POLY_STRUC */
    void Run_Poly_Method( struct POLY_STRUCT *poly );

#endif

In this part, I implemented typical functions that initializes, destroys struct and calls typical polymorphic method. In other scenarios, this methods can change or be extended.

C++
#include <stdlib.h>
#include "POLY_STRUC.H"

/*
Allocates an POLY_STRUCT struct,sets it polymorphic method 
and returns it
- void (*poly)()            : Polymorphic method to set
- return struct POLY_STRUCT    : Pointer to created struct,
NULL if allocation fails.
*/
struct POLY_STRUCT *InitPoly( void (*poly)() )
{
    /* Allocate struct */
    struct POLY_STRUCT *result = (struct POLY_STRUCT*)
                    malloc( sizeof( struct POLY_STRUCT ) );
    /* Test if allocation succeeds,if so set it's 
       polymorphic method */
    if(result != NULL)
        result->poly = poly;
    /* Return created struct */
    return result;
}

/*
Deallocates an POLY_STRUCT struct
- struct POLY_STRUCT *poly : Struct to deallocate
*/
void DestroyPoly( struct POLY_STRUCT *poly )
{ 
    if(poly != NULL) free(poly); 
}

/*
Runs a polymorphic method in a POLY_STRUCT
- struct POLY_STRUCT *poly_s : Struct to call its 
  polymorphic method
*/
void Run_Poly_Method( struct POLY_STRUCT *poly_s )
{ 
    (* ( poly_s->poly ) ) (); 
}
</stdlib.h>

And the sample main class to see how it works:

C++
#include <stdio.h>
#include <stdlib.h>
#include "POLY_STRUC.H"

/* Polymorphic Structures , this could be an set or array 
   of POLY_STRUC* */
struct POLY_STRUCT* example_poly1;
struct POLY_STRUCT* example_poly2;

/* Functions to assign for polymorphic structures */
void poly_example1_method(){printf("EXAMPLE1\n");}
void poly_example2_method(){printf("EXAMPLE2\n");}

int main(int argc, char *argv[])
{
    /* Initialize Polymorphic structures */
    example_poly1 = InitPoly(&poly_example1_method);
    example_poly2 = InitPoly(&poly_example2_method);    
    
    /* Execute polymorphic method in each structure */
    /* Polymorphic methos can be executed directly from 
       struc */
    /* This functions are added for modularity */
    Run_Poly_Method(example_poly1);
    Run_Poly_Method(example_poly2);
    
    /* Destroy initialized Polymorphic structures */
    DestroyPoly(example_poly1);
    DestroyPoly(example_poly2);
    return 0;
}
</stdlib.h></stdio.h>

Conclusion

In adapting polymorphism, function pointers plays the big role for the design. Also using structs is important for creating class oriented models. But, in the current circumstances we can not apply encapsulation in C(no private or protected modifiers).

It's obvious that polymorphism is more effective when it's used in OOP(with inheritance or composition). In this article, our goal is to use object oriented aspects in a structural language as much as we can ,to use advantages of it. But lack of dynamic binding, it's sure static and hard-coded.

What about the advantages and disadvantages? Trade-off between performance and problem-solution benefits(Using an object oriented design in projects simplifies solutions also increases reusability and extendibility) is main design consideration in this article. Performance impact is obvious. Calling functions by function-pointers is relatively slow. Also accessing struct members makes execution slower. But in the other side reusability and extendibility gain is sure obvious.

Adapting polymorphism brings some extra code implementations that makes relatively small projects more complex and unreadable. It's important to use polymorphism in big-scale projects(operating systems,hardware implementations etc...) to use it efficiently. But this disadvantage turns into an advantage when used in large scale projects.

Points of Interest

This was a quite different experience , like using C as C++.I know it's very important to use object oriented discrete from structural approach, but also it's also important to see the similarities. For a long time, I developed projects with object-oriented languages (C++, C#, JAVA) , using C again was quite enjoying. I think I'll continue enhancing this concept by adding other auxiliary methods.

History

Version 1.0 - Initial Version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Junior)
Turkey Turkey
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralSimilar Article Pin
«_Superman_»6-Dec-07 2:30
professional«_Superman_»6-Dec-07 2:30 
GeneralWhy to use Polymorphism in C Pin
Sudhir Mangla18-Feb-07 23:46
professionalSudhir Mangla18-Feb-07 23:46 
GeneralRe: Why to use Polymorphism in C Pin
Gokalp Peker19-Feb-07 6:05
Gokalp Peker19-Feb-07 6:05 
Generalright tool for the job Pin
Jim Crafton12-Feb-07 3:34
Jim Crafton12-Feb-07 3:34 
GeneralRe: right tool for the job Pin
Gokalp Peker12-Feb-07 3:57
Gokalp Peker12-Feb-07 3:57 
GeneralRe: right tool for the job Pin
Sceptic Mole13-Feb-07 2:00
Sceptic Mole13-Feb-07 2:00 
GeneralRe: right tool for the job Pin
Gokalp Peker13-Feb-07 2:16
Gokalp Peker13-Feb-07 2:16 
QuestionInteresting approach, 'OO'? Pin
Roland Pibinger11-Feb-07 6:50
Roland Pibinger11-Feb-07 6:50 
AnswerRe: Interesting approach, 'OO'? Pin
Gokalp Peker11-Feb-07 8:42
Gokalp Peker11-Feb-07 8:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.