Click here to Skip to main content
Click here to Skip to main content
Go to top

Polymorphism in C

, 10 Feb 2007
Rate this:
Please Sign up or sign in to vote.
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

#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.

#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:

#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

Share

About the Author

Gokalp Peker
Software Developer (Junior)
Turkey Turkey
No Biography provided

Comments and Discussions

 
GeneralSimilar Article Pinmember Santosh M. P. 6-Dec-07 2:30 
GeneralWhy to use Polymorphism in C PinmemberSudhir Mangla18-Feb-07 23:46 
GeneralRe: Why to use Polymorphism in C PinmemberGokalp Peker19-Feb-07 6:05 
Generalright tool for the job PinmemberJim Crafton12-Feb-07 3:34 
GeneralRe: right tool for the job PinmemberGokalp Peker12-Feb-07 3:57 
GeneralRe: right tool for the job PinmemberSceptic Mole13-Feb-07 2:00 
GeneralRe: right tool for the job PinmemberGokalp Peker13-Feb-07 2:16 
QuestionInteresting approach, 'OO'? PinmemberRoland Pibinger11-Feb-07 6:50 
AnswerRe: Interesting approach, 'OO'? PinmemberGokalp Peker11-Feb-07 8:42 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 10 Feb 2007
Article Copyright 2007 by Gokalp Peker
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid