Home > Backend Development > C++ > How to Separate Class Declaration and Implementation in C Header and Source Files?

How to Separate Class Declaration and Implementation in C Header and Source Files?

Susan Sarandon
Release: 2024-12-24 13:48:11
Original
428 people have browsed it

How to Separate Class Declaration and Implementation in C   Header and Source Files?

Separating Class Declaration and Implementation into Header and Source Files

Storing class declarations and member function implementations in separate header and source files is essential for modular and well-structured programming. Take, for instance, the following A2DD class:

class A2DD
{
private:
  int gx;
  int gy;

public:
  A2DD(int x, int y);
  int getSum();
};
Copy after login

Class Declaration in Header File

To separate the class declaration from its implementation, create a header file named A2DD.h, which contains only the class declaration without the implementation of the member functions. It should include include guards to prevent multiple inclusions:

// A2DD.h
#ifndef A2DD_H
#define A2DD_H

class A2DD
{
public:
  int gx;
  int gy;

public:
  A2DD(int x, int y);
  int getSum();
};

#endif
Copy after login

Note that as C class members are private by default, we have omitted the private access specifier.

Member Function Implementation in Source File

Next, create a corresponding source file named A2DD.cpp that contains the implementations 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;
}
Copy after login

The header file A2DD.h needs to be included in the source file A2DD.cpp to provide the necessary definitions.

By separating the class declaration and implementation into different files, you can effectively manage class definitions and reduce compilation time. This approach promotes code maintainability, reusability, and collaboration among developers.

The above is the detailed content of How to Separate Class Declaration and Implementation in C Header and Source Files?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template