Forward Declaration in C++

Here we are going to make a C++ program using forward declaration. So what is Forward declaration? Forward declaration refers to a prior declaration of a function, class, variable, syntax, etc. For example in code, if we need to declare a function say, “addition” we normally write it as void addition(int x, int y){ //body }. We can declare the function prior in code as void addition(); and then use the function afterward. 

The advantage of forward declaration is that the compiler takes less time in compiling thus increases the efficiency of code, this helps a lot in large projects. 

C++ program of forward declaration

#include <iostream>
using namespace std;
//forward declaration
    class Dog;
    class Cat;

//creating class "cat"
class Cat {

public:
    int i;

    void getdata(int n)
    {
        i = n;
    }
    friend int sum(Dog, Cat);
};
//creating class "dog"
class Dog {
public:
    int j;

    void getdata(int m)
    {
        j = m;
    }

};

//gives the sum
int sum(Dog m, Cat n)
{
    int result;
    result = m.j + n.i;
    return result;
}

int main()
{
    Cat b;
    Dog a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}

 

Function implementation 

  1. getdata() -:
    this function inserts data in public integer defined in the class.
  2. sum() -:
    this function gives the sum of two numbers. 

Implementation 

In the code first, we have two classes (forward declaration). Then we have implemented the class Cat and publicly defined an integer “i”. Afterward, with the help of the function getdata() we have inserted data in “i”. Then we call a function sum (this function is declared as a friend as it will take an integer from another class Dog so both the classes should be friends). Then we have implemented class Dog repeat the same steps as above except declaring function sum(). In main we firstly call function getdata() for both class which inserts data in both public integers “i” and “j” then we call function sum() which returns the sum of these two integers. 

Now if we haven’t declared classes at first (no use of forward declaration) then the code should have shown a compilation error. As in code, we can see that first, we are using class Dog in function sum and then implementing it. So, during using class Dog in the function, the compiler will show an error because according to compiler there is no class Dog. But if we use forward declaration the compiler won’t show any error. 

Output

The sum is : 9

Also read: Find the maximum GCD of the siblings of a Binary Tree using C++

Leave a Reply

Your email address will not be published. Required fields are marked *