Including file known to already be included

82 Views Asked by At

What's the convention when including a file you know is already included by another include?

Example: Class Base is declared in "base.h" and has a few child classes. Base has a virtual method foo(Bar& bar) and therefore includes "bar.h". From a proper convention standpoint, should we include "bar.h" in the child classes as well, given that the child classes include "base.h", which includes "bar.h"?

2

There are 2 best solutions below

0
On BEST ANSWER

Given that the declaration of a function only requires the parameters to be declared, you'll need to include the corresponding header. For known base classes or types of non-private data members the definition needs ro be included. Since everything else either only requires a declaration or is an implementation detail, you shouldn't rely on indirect headers being included.

0
On

One school of thought is that including both base.h and bar.h in child.h is better. Even though this is a virtual function dependency, including bar.h points future developer (who might not have an IDE) into the declaration without having to read base.h.

For non-virtual function, including both should be better imho, since another developer can change the content of base.h without having to worry about child.h's dependency on bar.h.