Object Oriented Programming In C

Overview

As most of us know, C language is an imperative (procedural) language and does not support Object Oriented Programming Concepts like information hiding, inheritance,polymorphism .. etc, from this sense, it seems to be hard to make our code reusable and maintainable.
Hence, we can ask what if we want to apply OOP, OOAD concepts in C language?! that’s we are going to talk about in our post.
We are going to write some posts related to this topic lets start with the first one

Abstract Data Types: Information Hiding

Data types are called abstract if we don’t show its representation to the user. Since the representation is not part of the definition, we are free to choose whatever is easiest or most efficient to implement. ADT introduces one of the programming principles which is Information Hiding.Simply, we can say that our target now is to separate the programming tasks of implementation and usage.

Let’s see an example:

  • note: this example is copied from (Object Oriented Programming In C –Axel-Tobias Schreiner )  with some modifications.

Car.h

#ifndef CAR_H_
#define CAR_H_

extern const void* Car;

void* SetModel(void* p_car, char* p_modelName);
void* SetID(void* p_car, int p_modelID);
char* GetName(void* p_car);
int* GetID(void* p_car);

#endif /* CAR_H_ */

Car.c

#include "Car.h"
#include
#include
#include
#include "New.h"
struct Car
{
	char* m_ModelName;
	int   m_ModelID;
};

static const size_t _Car = sizeof(struct Car);

const void * Car = & _Car;

void * new (const void * type, ...)
{	const size_t size = * (const size_t *) type;
	void * p = calloc(1, size);

	assert(p);
	return p;
}

void delete (void * item)
{
	free(item);
}

void* SetModel(void* p_car, char* p_modelName)
{
	struct Car * c= p_car;
	c->m_ModelName = p_modelName;
	return c;
}

void* SetID(void* p_car, int p_modelID)
{
	struct Car * c= p_car;
		c->m_ModelID = p_modelID;
		return c;
}

char* GetName(void* p_car)
{
	struct Car* c = p_car;
	return c->m_ModelName;
}
int* GetID(void* p_car)
{
	struct Car* c = p_car;
	return (int)c->m_ModelID;
}

New.h

#ifndef NEW_H_
#define NEW_H_

void * new (const void * type, ...);
void delete (void * item);

#endif /* NEW_H_ */

Main.c

#include
#include "Car.h"
#include "New.h"
int main ()
{
	void *newCar = new(Car);

	if(SetModel(newCar,"PMW"))puts("YES!!!");
	char* name = GetName(newCar);
	puts(name);
	(GetName(newCar))?puts("YES!!!"):puts("NO!!!");
	delete(newCar);
	(GetName(newCar))?puts("YES!!!"):puts("NO!!!");
		return 0;
}

References

Advertisements