Search code examples
coopheader-filescode-reuse

Header Files in C-language and Reusability of Object Oriented Programming?


In interview I was ask that as re-usability is one of the main advantages of Object Oriented Programming but it can also be achieved by include header files in C language? So what is the difference in OOP re-usability and C Header files?


Solution

  • If by "re-usability" you are simply implying that code does not need to be repeated in each code module, then yes, a header-file in C accomplishes that task because it allows the declarations for functions and variables defined with external linking in one code module to be used in another code module without the user having to re-type all those declarations and/or attempt to place every definition of every function that would normally be part of a library into each code module. Thus the duplication of code is prevented.

    Object-oriented programming through the use of inheritance and polymorphism in languages like C++ and Java have a similar effect ... you define an interface and/or a base-class once, and then you are able to "include" that code via inheritance in another class. Additionally, virtual methods along with polymorphism allows you to write functions that take a single base-class type as an argument, yet call code that is actually defined in a derived class-type. This essentially means you can call new code (i.e., your derived class), in old code (i.e., the function that accepted a base-class type). For instance, as a library developer, you could define a set of base-class types/interfaces, and a user could derived from those base-classes, yet still use them effectively in the same functions that were included with the library that accept arguments of the base-class type. Thus you are not forced to reduplicate those functions ... they are still usable by your "new" derived classes.