.h or .hpp : header file

The header files contain declarations (where classes and custom types are listed by name and type, and function prototypes give functions a type signature)

.cpp : source file

Source file contains implementation (where function bodies are actually defined, and some constant values are initialized).

header file example (Cube.h)

// All header (.h) files start with "#pragma once":
#pragma once

// A class is defined with the `class` keyword, the name
// of the class, curly braces, and a required semicolon
// at the end:
class Cube {
  public:  // Public members:
    double getVolume();
    double getSurfaceArea();
    void setLength(double length);

  private: // Private members:
    double length_;
};

Look at #pragma once at the begining.

Instructions beginning with # are special commands for the compiler, called preprocessor directives.

This instruction prevents the header file from being automatically included multiple times in a complex project, which would cause errors.

source file example (Cube.cpp)

#include "Cube.h"

double Cube::getVolume() {
  return length_ * length_ * length_;
}

double Cube::getSurfaceArea() {
  return 6 * length_ * length_;
}

void Cube::setLength(double length) {
  length_ = length;
}

Notice that the first thing it does in #include Cube.h to include all the text from the Cube.h file in the same directory.

Because the filename is specified in quotes, as Cube.h the compiler expects it t to be in the same directory as the current file.

Then, the file gives the definitions for the functions from the class definition before. These full source code listings for the functions that were declared previously are called the implementation.

It is common that function bodies will be implemented in the cpp file and not in the h file, but sometimes short class function bodies will be defined directly in the h file where they are declared inside the class declaration.

main.cpp

#include <iostream>
#include "Cube.h"

int main() {
  Cube c;

  c.setLength(3.48);
  double volume = c.getVolume();
  std::cout << "Volume: " << volume << std::endl;

  return 0;
}
  1. It includes a standard library header from the system directory. This is shown by the use of <> . Compiler look for the iostream header file in a system-wide library path that is located outside of your current directory.
  2. #include "Cube.h" just like in the Cube.cpp . You have to include the necessary headers in every cpp file where they are needed. However, you shouldn’t use #include to literally include one cpp file in another. No need to write #include "Cube.cpp", because the function definitions in the Cube.cpp`` will be compiled separately and then linked to the code from the main.cpp file.

Untitled