Sorry for the newbie question, but what are header files? What should they contain? Just classes and definitions?

Dani AI

Generated

Header files (.h / .hpp) serve as a module’s public interface: they declare the names, types, and contracts that other translation units use while keeping most of the implementation details in .cpp files. This builds on ’s mention of declarations and on ’s “skeleton” idea: headers say what is available; sources show how it works.

Typical things to put in headers: class/struct declarations, function prototypes, type aliases, enum / enum class definitions, constexpr constants and small inline accessors, template definitions (templates must be visible at compile time), and forward declarations to reduce coupling. Things to avoid in headers: large non-inline function bodies, definition of non-const globals, heavy includes that can be forward-declared, and any using namespace directives — these leak into every file that includes the header and cause subtle problems. For globals prefer extern in the header and a single definition in a .cpp.

A minimal, idiomatic header pattern:

#ifndef MYLIB_WIDGET_H
#define MYLIB_WIDGET_H

#include <string> // include only what the header needs

class Widget {
public:
    Widget();
    void draw() const; // declaration only; implementation in Widget.cpp
private:
    struct Impl;     // forward declaration to hide implementation
    Impl* pimpl;
};

extern const int DefaultTimeout; // define in one .cpp file

#endif // MYLIB_WIDGET_H

Practical rules of thumb: use include guards or #pragma once; make headers self-sufficient (they should compile if included alone); include the corresponding header first in a .cpp to catch missing dependencies; prefer forward declarations to cut build time; and use the PIMPL idiom or move heavy dependencies into the .cpp to keep the public header small and stable. This complements the points already raised by and and answers the original question from about what belongs in a header.

Recommended Answers

All 3 Replies

If possible, header should contain a skeleton for the desired Object.
For example a header might contain a class skeleton named Car, and you might define
the actual implementation of Car in a different .cpp file. Another example, you
might declare some functions in a header, but do the actual implementation in a different .cpp file.

//BestClassInUniverse.h
// this header defines the skeleton for the BestClassInUniverse
class BestClassInUniverse{
public:
  void doTheBestThingInUniverse(); //skeleton
};
//BestClassInUniverse.cpp
//actually defines the implementations
BestClassInUniverse::doTheBestThingInUniverse(){
  //some  top secret code.
}

Thanks. I understand it now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.