Click here to Skip to main content
15,895,799 members
Articles / Programming Languages / C

Inheritance and Polymorphism in C

,
Rate me:
Please Sign up or sign in to vote.
4.74/5 (35 votes)
10 Sep 2010CPOL5 min read 235.8K   1.3K   65  
Implementation of single level inheritance and polymorphism in C.
#include "person.h"




Person* new_Person(const char* pFName, const char* pLName)
{
	Person* pObj = NULL;
	//allocating memory
	pObj = (Person*)malloc(sizeof(Person));
	if (pObj == NULL)
	{
		return NULL;
	}
	pObj->pDerivedObj = pObj; //pointing to itself
	pObj->pFirstName = malloc(sizeof(char)*(strlen(pFName)+1));
	strcpy(pObj->pFirstName, pFName);
	pObj->pLastName = malloc(sizeof(char)*(strlen(pLName)+1));
	strcpy(pObj->pLastName, pLName);

	//Initializing interface for access to functions
	pObj->Delete = delete_Person;			//destructor pointing to destrutor of itself
	pObj->Display = Person_DisplayInfo;
	pObj->WriteToFile = Person_WriteToFile;

	return pObj;
}




void delete_Person(Person* const pPersonObj)
{
	if(pPersonObj!= NULL)
	{
		free(pPersonObj->pFirstName);
		free(pPersonObj->pLastName);
		free(pPersonObj);
	}
}




void Person_DisplayInfo(Person* const pPersonObj)
{
	printf("FirstName: %s\n", pPersonObj->pFirstName);
	printf("LastName: %s\n", pPersonObj->pLastName);
}





void Person_WriteToFile(Person* const pPersonObj, const char* pFileName)
{
	// code for writing Person information to file
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

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

Comments and Discussions