Forward Declarations and Includes - c++

When working with a library, whether it be my own or external, there are lot of classes with forward declarations. The same classes also have includes as well depending on the situation. When I use a certain class, I need to know whether certain objects that the class uses, are forward declared or are they #include(d). The reason is I want to know whether I should be including both headers or just one.
Now I know it is fairly simple to check, just compile (or go through all the headers until you find the object in question either #include(d) or forward declared). But with large projects, a simple compile takes a long time, and going into each include file to check whether the class in question is being included or forward declared is tedious, especially if it is a few levels deep. To illustrate the problem further:
Class A is a Class B is a Class C
which has a pointer to Class Foo
I include Class A and want to know whether Class Foo is ready for use right away, or whether I have to do the following:
#include "ClassA.h"
#include "ClassFoo.h"
So, is there a quick and easy way to find out about this dependency without compiling or going into the depended headers? (one of the reasons I ask this question is because I want to eventually make an add-in for VS and/or stand-alone program for this if the functionality does not already exist)
Thanks!

In a source file you should not depend on what the other header files include.
You should explicitly include every type that your code depends on.
If you do not use a type (ie just passing a pointer or a reference around) then you don't need its definition so don't include its header file (The header file for the methods you are using should have at least a forwward declaration).
So in your particular instance it is hard to tell.
Is you source file explicitly uses any members from Foo then you need to include "ClassFoo.h" otherwise don't. There is no need to go digging around in header files (they may change anyway). Just check exactly what your source file uses and include those (and only those) header files.
In the header file: Prefer forward declaration to inclusion. This way you limit/break circular dependencies.

Actually I am finding eliminating as many header includes as is humanly possible actually helps hella more. See this answer. By cutting out more #include statements, its much more clear exactly what is part of the source file (#includes are a blackbox - you never know what is getting linked in by that one line of text). If a class Foo needs the implementation details of a class Bar, then Foo.h should not include "Bar.h", but rather, contain only a forward declaration. Foo.cpp should include Bar.h.
Foo.h
class Bar ; // fwd declare wherever possible
class Foo
{
// I can haz needs Bar
void do( Bar *bar ) ;
} ;
Foo.cpp
#include "Foo.h"
#include "Bar.h" // I can has needs complete implementation details.
Foo::do( Bar *bar )
{
}
Bar.h
class Bar
{
// code..
} ;

If you're using class A then you should only care about the private interface of the base class C (and possibly additional interface in A. If the class is designed properly, you won't need to access Foo directly because it will be encapsulated in C's interface and not exposed to the public world. In this case you won't need an include to Foo at all because it's not part of C's public interface. If in fact Foo is part of the interface to C in some way, then I argue that C.h should include Foo.h as well, so that clients can use it without having to make the determinations you're asking about.

Related

forward declaration of classes, splitting variables and functions [duplicate]

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 9 years ago.
Do you have any good advice on how to avoid circular dependencies of header files, please?
Of course, from the beginning, I try to design the project as transparent as possible. However, as more and more features and classes are added, and the project gets less transparent, circular dependencies start happening.
Are there any general, verified, and working rules? Thanks.
If you have circular dependency then you doing something wrong.
As for example:
foo.h
-----
class foo {
public:
bar b;
};
bar.h
-----
class bar {
public:
foo f;
};
Is illegal you probably want:
foo.h
-----
class bar; // forward declaration
class foo {
...
bar *b;
...
};
bar.h
-----
class foo; // forward declaration
class bar {
...
foo *f;
...
};
And this is ok.
General rules:
Make sure each header can be included on its own.
If you can use forward declarations use them!
Use forward declarations where possible.
Move any header includes out of a header file and into the corresponding cpp file if they are only needed by the cpp file. Easiest way to enforce this is to make the #include "myclass.h" the first include in myclass.cpp.
Introducing interfaces at the point of interaction between separate classes can help reduce dependencies.
Some best practices I follow to avoid circular dependencies are,
Stick to OOAD principles. Don't include a header file, unless the class included is in composition relationship with the current class. Use forward declaration instead.
Design abstract classes to act as interfaces for two classes. Make the interaction of the classes through that interface.
A general approach is to factor out the commonalities into a third header file which is then referenced by the two original header files.
See also Circular Dependency Best Practice
depending on your preprocessor capabilities:
#pragma once
or
#ifndef MY_HEADER_H
#define MY_HEADER_H
your header file
#endif
If you find it very boring to design header files maybe makeheaders from Hwaci (designers of SQLite and fossil DVCS) could be of interest for you.
What you're aiming at is a layered approach. You can define layers where modules can depend on lower layer modules but the inverse should be done with observers. Now you can still define how fine-grained your layers should be and whether you accept circular dependency within layers, but in this case I would use this.
In general header files should forwardly declare rather than include other headers wherever possible.
Also ensure you stick to one class per header.
Then you almost certainly will not go wrong.
The worst coupling usually comes from bloated template code. Because you have to include the definition inside the header, it often leads to all kinds headers having to be included, and then the class that uses the template includes the template header, including a load of other stuff.
For this reason, I would generally say: be careful with templates! Ideally a template should not have to include anything in its implementation code.
Altough Artyom provided best answer this tutorial is also great and provides some extenstions http://www.cplusplus.com/forum/articles/10627/

Why do we use #includes if forward declarations seem to be superior?

I've recently run into the idea of forward declarations within C++. I have read that by using forward declarations, compile times can be quickened by avoiding unnecessary declarations and recursive #includes. However, this has got me wondering, why exactly does anyone use #includes then?
Are there situations where plain forward declarations just aren't reasonable? Such as if you have a library header file, it would just make more sense to have a single #include then naming each class/function prototype?
I've read many posts on stack overflow explaining the differences between each path, but why exactly use #includes?
The main reason for including headers, rather than using forward declarations throughout your code, is enforcing consistency with minimal duplication.
Consider a header used in several cpp files. When a class or a variable changes in the header, you would need to find and change all references in all files. Otherwise, the code would continue compiling, but it would fail to link.
In addition, forward declarations have their limits: they let you declare pointer to classes or call functions, but they do not allow creating instances or accessing their members.
It is simply that forward declarations you have in mind cannot replace declarations in headers.
One obvious example is the declaration of class:
Assuming I have a Foo class and is going to contains Bar:
This will work
// FOO.H
class Bar;
class Foo {
private:
Bar* bar;
};
But this won't:
// FOO.H
class Bar;
class Foo {
private:
Bar bar;
};
There is a lot of cases that compiler needs to know the "full" declaration (which we usually put in headers) in order to do its work, instead of just a forward declaration containing the name of class etc (which allow you to mostly create pointer/reference to such class).

Including file known to already be included

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"?
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.
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.

Hiding library dependencies from library users

Consider I'm writting a static library. Let it has a class Foo
// mylib.h
#include <dependency_header_from_other_static_library.h>
class Foo {
// ...
private:
type_from_dependent_library x;
}
As you can see this library (let call it mylib) depends on another library. It compiles well. But when user compile it's code (that uses Foo and includes mylib.h) and linking with my lib the compilation fails, because user need to have dependency_header_from_other_static_library.h header file to compile code as well.
I want to hide this dependency from the user. How this can be done? The one thing that comes to mind is a PIMPL idiom. Like:
// mylib.h
#include <dependency_header_from_other_static_library.h>
class Foo {
// ...
private:
class FooImpl;
boost::shared_ptr<FooImpl> impl_;
}
// mylib_priv.h
class FooImpl {
// ...
private:
type_from_dependent_library x;
}
But it requires me to duplicate the interface of the class Foo in FooImpl. And, is it an overkill to use PIMPL in my case?
Thanks.
When decoupling a header from other headers, there are a few approaches you might be able to use:
If the used library makes a promise about how it declares its types, you may be able to forward declare the needed types in your header. Of course, this still means you can only refer to these types as pointers or in function signatures in the header but this may be good enough. For example, if the used library promises to have a class LibraryType that you need to use, you can do something like this:
// Foo.h
class LibraryType;
class Foo {
// ...
LibraryType* data;
};
This may cut you the necessary slack to use the type without including its header and without jumping through a PImpl approach.
If the library doesn't make a promise about how it declares it types you may use void* to refer to the corresponding types. Of course, this means that whenever you access the data in your implementation, you'll need to cast the void* to the appropriate type. Since the type is statically known, using static_cast<LibraryType*> is perfectly fine, i.e., there isn't any overhead due to the cast, but it is still relatively painful to do.
The other alternative is, of course, to use the PImpl idiom. If you type provides any reasonably service, it will probably change the interface quite a bit and it shouldn't amount much to replicating the interface between the class itself and the privately declared type. Also, note that the private type is just a data container, i.e., it is reasonably to just make it a struct and have no protection to its accesses. The only real issue is that you need to make sure that the type's definition is visible at the point where the destructor is called. Using std::shared_ptr<T>(new T(/*...*)) arranges for this.
Effectively, all three approaches do the same thing although with slightly different techniques: they provide you an opaque handle to be used in the header file whose definition is only known to the implementation. This way, the client of the library doesn't need to include the corresponding header files. However, unless the symbols are resolved when building the library, it would still be necessary for the client to have access to the used library.

Avoiding Circular Dependencies of header files [duplicate]

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 9 years ago.
Do you have any good advice on how to avoid circular dependencies of header files, please?
Of course, from the beginning, I try to design the project as transparent as possible. However, as more and more features and classes are added, and the project gets less transparent, circular dependencies start happening.
Are there any general, verified, and working rules? Thanks.
If you have circular dependency then you doing something wrong.
As for example:
foo.h
-----
class foo {
public:
bar b;
};
bar.h
-----
class bar {
public:
foo f;
};
Is illegal you probably want:
foo.h
-----
class bar; // forward declaration
class foo {
...
bar *b;
...
};
bar.h
-----
class foo; // forward declaration
class bar {
...
foo *f;
...
};
And this is ok.
General rules:
Make sure each header can be included on its own.
If you can use forward declarations use them!
Use forward declarations where possible.
Move any header includes out of a header file and into the corresponding cpp file if they are only needed by the cpp file. Easiest way to enforce this is to make the #include "myclass.h" the first include in myclass.cpp.
Introducing interfaces at the point of interaction between separate classes can help reduce dependencies.
Some best practices I follow to avoid circular dependencies are,
Stick to OOAD principles. Don't include a header file, unless the class included is in composition relationship with the current class. Use forward declaration instead.
Design abstract classes to act as interfaces for two classes. Make the interaction of the classes through that interface.
A general approach is to factor out the commonalities into a third header file which is then referenced by the two original header files.
See also Circular Dependency Best Practice
depending on your preprocessor capabilities:
#pragma once
or
#ifndef MY_HEADER_H
#define MY_HEADER_H
your header file
#endif
If you find it very boring to design header files maybe makeheaders from Hwaci (designers of SQLite and fossil DVCS) could be of interest for you.
What you're aiming at is a layered approach. You can define layers where modules can depend on lower layer modules but the inverse should be done with observers. Now you can still define how fine-grained your layers should be and whether you accept circular dependency within layers, but in this case I would use this.
In general header files should forwardly declare rather than include other headers wherever possible.
Also ensure you stick to one class per header.
Then you almost certainly will not go wrong.
The worst coupling usually comes from bloated template code. Because you have to include the definition inside the header, it often leads to all kinds headers having to be included, and then the class that uses the template includes the template header, including a load of other stuff.
For this reason, I would generally say: be careful with templates! Ideally a template should not have to include anything in its implementation code.
Altough Artyom provided best answer this tutorial is also great and provides some extenstions http://www.cplusplus.com/forum/articles/10627/