-1

So i've just read about forward declarations at various sources (e.g googles c++ style guide) and i am quite confused when i should and when i shouldn't use forward declarations.

One one hand if I always forward declare classes i will never have troubles with circular dependencies and faster compile times.
But on the other hand i will have to use almost exclusively work with pointers to objects which seems quite unsafe considering memory leaks and also unnecessary complicated to work with.

So should i use forward declarations whenever I possibly can or only when its needed to avoid stuff like circular dependencies?

And another question regarding forward declarations. If im working with extern libraries such as GLM (which is a math library) and i need it in many different classes is there a way to forward declare those aswell / does it even make sense to do so?

Examples of what i have to include (GLM):

#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>

And for example i will use it like this:

std::vector <glm::vec3> vertices;
heap_trouble
  • 123
  • 2
  • 10

1 Answers1

1

Generally forward declarations end up being necessary only if there is some sort of circular dependency, and generally should be avoided.

So the version that says 'only for circular dependencies' is more on the right track.

"Pointers to objects" is not really relevant to the question, as in modern C++ normally raw pointers should be avoided most of the time anyway, using one of the now standard smart pointers instead, or better yet, references. Depending on what you are trying to do, keeping class members out of the class headers using Pimpl or fast pimpl idioms might be a good practice as well.

To last part of your question, what you probably want to do is to include the dependency external library headers that you commonly use in a single header file of your own, and then just include this file in your code modules where required. This can potentially give an advantage in compilation times too, if you have set up to use precompiled headers.

kert
  • 2,161
  • 21
  • 22
  • So it is not worth changing up every member variable to (smart) pointers just so i could forward declare, is that right? – heap_trouble Nov 05 '15 at 22:12
  • 1
    Storage and life cycle management, i.e. whether a particular data element is allocated on stack or heap, and whether it is accessed via a reference, pointer, smart pointer or some other means in a particular class, should normally not be driven by declaration requirements at all. Avoid forward declarations in most cases. – kert Nov 06 '15 at 00:42