I have a problem regarding multiple inclusion of header file in C++ code.
Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this.
class Z { …some code… };
class X: public Z { …some code… }; //here #include header of class Z added
class Y: public Z //here #include header of class Z added as well as of X class
{
private:
X* mX; //instance of X
…some code…
};
So in this multiple definition of all methods of base class arises. How can I cope with this problem?
Using “include guards” (Wikipedia link)
This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change
MYHEADER_Hto something specific to you, for example if the header defines a class namedCustomerAccount, you can call the guardCUSTOMERACCOUNT_H.In your specific case, have a separate header/source file for each class. The header file for the Z class will have an include guard:
Now, the headers of both X and Y can include
z.hsafely – it will only really be included once in a.cppfile that includes bothx.handy.hand no duplication will occur.Always keep in mind that in C and C++ what’s really gets compiled are the source (.c or .cpp) files, not the header files. The header files are just “copy-pasted” by the preprocessor into the sources files that
includethem.