Separating Class Declarations and Member Function Implementations in Header and Source Files
When working with complex C programs, it becomes necessary to separate the declarations of a class and its member function implementations into separate files for organizational and maintenance purposes. This article addresses the common question of how to accomplish this separation.
Problem:
Consider the following class:
class A2DD { private: int gx; int gy; public: A2DD(int x,int y); int getSum(); };
How do we separate this class's declaration and member function implementations into a header file and a source file?
Solution:
Step 1: Create a Header File:
The header file, typically named with the extension ".h", contains the class declaration. To prevent multiple inclusion errors, include guards are used:
// A2DD.h #ifndef A2DD_H #define A2DD_H class A2DD { int gx; int gy; public: A2DD(int x,int y); int getSum(); }; #endif
Step 2: Create a Source File:
The source file, typically named with the extension ".cpp", contains the implementation of the member functions:
// A2DD.cpp #include "A2DD.h" A2DD::A2DD(int x,int y) { gx = x; gy = y; } int A2DD::getSum() { return gx + gy; }
In the header file, note the absence of the "private" keyword. By default, class members in C are private. The #include guards ensure that the header file is not included multiple times, preventing compilation errors.
This approach allows you to easily manage the interface and implementation of your class separately, enhancing code readability and maintainability.
The above is the detailed content of How to Separate Class Declarations and Member Function Implementations in C Header and Source Files?. For more information, please follow other related articles on the PHP Chinese website!