Should you forward declare classes that are part of a library?

Is it ok to declare classes that are part of a library that your using or should you only forward declare classes that you made?

For example:

1
2
3
4
5
6
7
8
9
10
11
12

namespace std
{
    class system_clock; // Part of the C++ standard library.
}


namespace sf
{
    class RenderWindow; // Part of the SFML library.
}


Last edited on
Is it ok to declare classes that are part of a library that your using or should you only forward declare libraries that you made?

Generally, you should only forward-declare names defined in your own code. This is because forward declarations often rely on implementation details that you shouldn't depend on.

Specifically, your first example is forbidden; the second is merely a bad idea.

In general, the documented interface of a function or function may not match the implementation - a thing that's documented as a function might be a class; a thing that looks like a class might actually be a class template. There might be default arguments involved, or candidates that you don't know about. Any reliance on these details immediately makes your code non-portable between different implementations of the same library.

The first case is wrong for two reasons:
1. it is undefined behavior to add to namespace std, except template specializations when certain specific conditions are met.
2. std::string is not a class, but an alias of a template specialization, whose implementation you can't depend on.

I have no idea whether the second one is correct, but it's surely bad practice. Just include the file you need.
Last edited on
Thanks for the help!
The biggest advantage of using forward declarations is to avoid circular dependencies, something that is not a problem when other libraries.
Topic archived. No new replies allowed.