Thread: When to forward reference and when to include?

  1. #1
    Registered User
    Join Date
    Feb 2020

    When to forward reference and when to include?

    Headers and Includes: Why and How says -

    If, for example, class A uses class B, then class B is one of class A's dependencies. Whether it can be forward declared or needs to be included depends on how B is used within A:

    - do nothing if: A makes no references at all to B
    - do nothing if: The only reference to B is in a friend declaration
    - forward declare B if: A contains a B pointer or reference: B* myb;
    - forward declare B if: one or more functions has a B object/pointer/reference
    as a parementer, or as a return type: B MyFunction(B myb);
    - #include "b.h" if: B is a parent class of A
    - #include "b.h" if: A contains a B object: B myb;
    Is it as simple as that or is there something more to it?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    After you replace "class" with "struct", it's even simpler because friendship, references, and parents don't exist in C, and you don't have to worry about the case where a member function that is defined inline in a class definition directly instantiates an object because member functions don't exist in C either.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Feb 2020
    :+1: Thank you very much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Does #include indirectly include the source file too?
    By Lord Asriel in forum C Programming
    Replies: 10
    Last Post: 11-30-2011, 08:20 AM
  2. Replies: 1
    Last Post: 11-06-2011, 06:20 PM
  3. #include <windows.h> and #include <wininet.h>
    By steve1_rm in forum C++ Programming
    Replies: 4
    Last Post: 03-30-2009, 11:14 AM
  4. Which came first? #include <stdio.h> or #include <stdlib.h> ?
    By Brian in forum A Brief History of
    Replies: 6
    Last Post: 01-14-2002, 10:58 PM

Tags for this Thread