Forward declaration vs pragma once

Doesn’t the pragma once compiler directive already take care of making sure header files are only taken into consideration one time during the compilation process? If so, then why would taking care of forward declarations and not including header files where they’re technically not needed make any improvements to compilation time?

#pragma once only prevents a header being included multiple times in the same translation unit (compilation of a source file after the preprocessor has run, essentially)

So for example if I had the header files Wheel.h and Car.h

// Wheel.h
#pragma once
class Wheel
{
};

// Car.h
#pragma once
#include "Wheel.h"
class Car
{
    Wheel* Front;
};

Then in a source file I had

#include "Wheel.h"
#include "Car.h"

Without #pragma once I would get 2 copies of Wheel.h

Demo: Compiler Explorer
The right hand side shows the preprocessed output.

This is the only thing #pragma once solves. It does not prevent including a header that is not needed.
That example of “Car.h” does not need to include “Wheel.h” yet it does so anyway. This forces any inclusion of “Car.h” to also include “Wheel.h” whether it needed it or not.

Now imagine “Wheel.h” was huge and also included a lot of files. ALL files including “Car.h” would get those too.


To enable using the output stream insertion operator for your user defined type you do so by overloading this operator

std::ostream& operator<<(std::ostream&, const YourType&);

As it’s taken by reference you don’t need the full definition of std::ostream, you just need to tell the compiler what it is i.e. you need a forward declaration. Doing so is non-trivial and I’m not sure that’s even permitted by the standard. However there is a header to serve that exact purpose for the iostreams.

Compare the preprocessed line count

with <iostream>
with <iosfwd>

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms