Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
forward_list::cbefore_begin() in C++ STL
Next article icon

What are Forward declarations in C++

Last Updated : 28 Nov, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program).

Example:

  // Forward Declaration of the sum()  void sum(int, int);    // Usage of the sum  void sum(int a, int b)  {      // Body  }  

In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this.

Example:

  // Forward Declaration class A  class A;    // Definition of class A  class A{      // Body  };  

Need for Forward Declarations:

Let us understand the need for forward declaration with an example.

Example 1:




.
// C++ program to show
// the need for Forward Declaration
  
#include <iostream>
    using namespace std;
  
class B {
  
public:
    int x;
  
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
class A {
public:
    int y;
  
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
  
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}
 
 

Output:

  Compile Errors :  prog.cpp:14:18: error: 'A' has not been declared     friend int sum(A, B);                    ^  

Explanation: Here the compiler throws this error because, in class B, the object of class A is being used, which has no declaration till that line. Hence compiler couldn’t find class A. So what if class A is written before class B? Let’s find out in the next example.

Example 2:




.
// C++ program to show
// the need for Forward Declaration
  
#include <iostream>
    using namespace std;
  
class A {
public:
    int y;
  
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
  
class B {
  
public:
    int x;
  
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}
 
 

Output:

  Compile Errors :  prog.cpp:16:23: error: 'B' has not been declared       friend int sum(A, B);                         ^  

Explanation: Here the compiler throws this error because, in class A, the object of class B is being used, which has no declaration till that line. Hence compiler couldn’t find class B.

Now it is clear that any of the above codes wouldn’t work, no matter in which order the classes are written. Hence this problem needs a new solution- Forward Declaration.

Let us add the forward declaration to the above example and check the output again.

Example 3:




#include <iostream>
using namespace std;
  
// Forward declaration
class A;
class B;
  
class B {
    int x;
  
public:
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
class A {
    int y;
  
public:
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}
 
 
Output:
  The sum is : 9  

The program runs without any errors now. A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.



Next Article
forward_list::cbefore_begin() in C++ STL

S

SidharthSunil
Improve
Article Tags :
  • C++
  • Programming Language
  • CPP-Basics
Practice Tags :
  • CPP

Similar Reads

  • forward_list cbegin() in C++ STL
    The forward_list::cbegin() is a function in C++ STL which returns a constant iterator pointing to the first element of the forward_list. Syntax: forward_list_name.cbegin() Parameters: This function does not accept any parameter. Return Value: This function returns an iterator that points to the cons
    2 min read
  • std::forward in C++
    In C++, std::forward() is a template function used for achieving perfect forwarding of arguments to functions so that it's lvalue or rvalue is preserved. It basically forwards the argument while preserving the value type of it. std::forward() was introduced in C++ 11 as the part of <utility> h
    3 min read
  • Difference Between Forward List and List in C++
    Forward List is a sequence container that allows unidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Singly Linked List, which requires constant time for insertion and deletion. Elements of the forward list are scattered in the memor
    3 min read
  • forward_list::before_begin() in C++ STL
    forward_list::before_begin() is an inbuilt function in C++ STL that returns an iterator that points to the position before the first element of the forward_list. Forward list in STL is a singly linked list implementation. This function comes under the <forward_list> header file. Syntax: forwar
    1 min read
  • forward_list::cbefore_begin() in C++ STL
    forward_list::cbefore_begin() is an inbuilt function in CPP STL which returns a constant random access iterator which points to the position before the first element of the forward_list. The iterator obtained by this function can be used to iterate in the container but cannot be used to modify the c
    2 min read
  • What are Reference Collapsing Rules in C++?
    In C++, we have a very useful feature called reference collapsing, which comes into play when dealing with references to references, especially in the context of templates. It is very important to make templates work seamlessly with references, ensuring that code behaves consistently and as expected
    4 min read
  • Forward Iterators in C++
    After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ? Forward iterators are one of the five main t
    6 min read
  • Functions that cannot be overloaded in C++
    In C++, following function declarations cannot be overloaded. 1) Function declarations that differ only in the return type. For example, the following program fails in compilation. C/C++ Code #include&lt;iostream&gt; int foo() { return 10; } char foo() { return 'a'; } int main() { char x = f
    3 min read
  • Can a constructor be private in C++ ?
    Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be
    3 min read
  • forward_list::clear() and forward_list::erase_after() in C++ STL
    Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences