Search code examples
c++classoopheader-filesmember-functions

How to separate a class and its member functions into header and source files


I am confused on how to separate implementation and declarations code of a simple class into a new header and cpp file. For example, how would I separate the code for the following class?

class A2DD
{
  private:
  int gx;
  int gy;

  public:
  A2DD(int x,int y)
  {
    gx = x;
    gy = y;
  }

  int getSum()
  {
    return gx + gy;
  }
};

Solution

  • The class declaration goes into the header file. It is important that you add the #ifndef include guards. Most compilers now also support #pragma once. Also I have omitted the private, by default C++ class members are private.

    // A2DD.h
    #ifndef A2DD_H
    #define A2DD_H
    
    class A2DD
    {
      int gx;
      int gy;
    
    public:
      A2DD(int x,int y);
      int getSum();
    
    };
    
    #endif
    

    and the implementation goes in the CPP file:

    // A2DD.cpp
    #include "A2DD.h"
    
    A2DD::A2DD(int x,int y)
    {
      gx = x;
      gy = y;
    }
    
    int A2DD::getSum()
    {
      return gx + gy;
    }