Introduction to Functions

When to Use Forward Declarations in C++

In what situations should I use forward declarations in my C++ code?

Abstract art representing computer programming

Forward declarations are useful in a few scenarios:

  1. To break circular dependencies. If two classes or functions depend on each other, one of them can use a forward declaration to break the cycle.
  2. To improve compilation speed. If a header file only uses pointers or references to a type, it can forward declare that type instead of #include-ing its definition. This reduces the amount of code that needs to be parsed when the header is included.

For example, consider these two classes:

class A {
  B* b;
  // ...
};

class B {
  A* a;
  // ...
};

This code won't compile, because A needs to know about B, and B needs to know about A. We can fix this with a forward declaration:

class B; // Forward declaration

class A {
  B* b;
  // ...
};

class B {
  A* a;
  // ...
};

Now A knows that B exists (but not its full definition), which is enough for it to have a B* member.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved