Forward Declaration in C++

Suneet Agrawal
2 min readNov 16, 2024

--

In C++, `forward declaration`` is a powerful tool that allows you to declare the existence of various entities before providing their full definitions. This technique is particularly useful for resolving circular dependencies, improving code organization, and optimizing compile times. In this blog post, we will explore forward declaration for a wide range of C++ entities, including classes, structs, enums, functions, variables, namespaces, class templates, and even friend functions.

This post was originally posted at https://agrawalsuneet.github.io/blogs/forward-declaration-in-c++/ and later reposted on Medium.

Forward Declaration for Classes

One of the most common use cases for forward declaration is dealing with classes, especially in situations where two classes depend on each other. Here’s an example of forward declaring two classes, ClassA and ClassB, to break a circular dependency:

// Forward declaration for ClassB
class ClassB;

class ClassA {
public:
ClassB* bInstance;
};

class ClassB {
public:
ClassA* aInstance;
};

Forward Declaration for Structs

Structs can also be forward declared in a similar way to classes. Here’s an example where two structs, StructX and StructY, reference each other:

// Forward declaration for StructY
struct StructY;

struct StructX {
StructY* yInstance;
};

struct StructY {
StructX* xInstance;
};

Forward Declaration for Enums

Enums can be forward declared when you need to use them before their actual definition.

Please continue reading at https://agrawalsuneet.github.io/blogs/forward-declaration-in-c++/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

No responses yet