How do we decide whether to put #include statements in the header or cpp file?

How do we decide whether to put #include statements in the header or cpp file? Why is there even the option to do both?

And in relation to that, why have the header in a separate file?

Only include in the header if you absolutely need to. You would need to do that if you need its size, access its members or you’re inheriting from it. As all of those would need the class definition.

When you have a pointer to something you don’t need its size as the size of a pointer is the same regardless to what it points to.

class Example1
    int Value1 = 0;
    bool Value2 = false;
    char Value3 = 'c';

C++ needs to know the size of each of those variables so it knows how big Example1 is and how to lay out an instance of that type in memory.


Would probably report Example1 being the sizeof 8 bytes (4 + 1 + 1 + 2 padding bytes for 4 byte alignment). If you change those types to be something else you could change the layout and/or the size of the class. For example if you change Value2 to int you would increase the size to 12 with 3 padding bytes. (Should note that the size of primitive types in C++ aren’t guaranteed to be a certain size)

But if they’re all pointers, changing what type they point to doesn’t change the size of the type at all.

So that you can compile the files separately whilst also being able to get the class definition in multiple files where it’s needed. Detailed answer:


Thankyou for this.

1 Like

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

Privacy & Terms