Home > Backend Development > C++ > How to Separate Class Declarations and Member Function Implementations in C Header and Source Files?

How to Separate Class Declarations and Member Function Implementations in C Header and Source Files?

Patricia Arquette
Release: 2024-12-26 05:46:11
Original
789 people have browsed it

How to Separate Class Declarations and Member Function Implementations in C   Header and Source Files?

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();
};
Copy after login

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
Copy after login

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;
}
Copy after login

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!

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