Creating a C++ reusable Header File and its Implementation Files
Reusability is one of the most important concepts of Software Engineering. Reusability means developing code that can be reused either in the same program or in different programs. C++ allows reusability through inheritance, containership, polymorphism, and genericity. But, there is another way to define independent building blocks. This can be achieved by creating header files and implementation files.
Header files are the files that include the class declaration. The name of the class is generally the same as that of the header file. (For example, a LinkedList class will be stored inside a LinkedList.h header file)Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
On the other hand, the implementation file consists of the function definition of the class which was defined inside the header file. Generally, the file name is the name of the class, with a .cpp extension. (For example, a LinkedList class’s function definition will be stored inside a LinkedList.cpp header file)
Now, to create an object of the class, defined in the above header file, there must be a main() function. But wait, where to define a main() function, particularly, which file?
The main function is defined inside another file, known as the driver file, or, in some cases, the client file.
Example: Here, complexNum class is implemented. It is split up into two files. The header file has the extension.h and contains the class definitions.
Now to check for correctness and to implement the above complexNum class, there is a need for a driver file. Below is the driver file:
The header, implementation as well as driver files should be in the same folder. Otherwise, provide the link of the present working directory in the include statements.
Header files are already used by programmers, which are very useful, and become handy while implementing various data structures and algorithms. For example, dynamic arrays can be implemented using <vector> header file.
Advantages Of Storing Class Definition In Different Files:
- Inheritance can be used to achieve code reusability, but the drawback of it is that a class has to be inherited from a class inside the same file. One cannot inherit a class from a different file.
- But, this issue is resolved by using the header and implementation files, hence making the class reusable.
- If the class implementation doesn’t change, then there is no need to recompile it.