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.
// 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.
// C++ program to show // the need for Forward Declaration using namespace std; void getdata( int n) friend int sum(A, B); void getdata( int m) friend int sum(A, B); int sum(A m, B n) int result; result = m.y + n.x; return result; cout << "The sum is : " << sum(a, b);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.
// C++ program to show // the need for Forward Declaration using namespace std; void getdata( int m) friend int sum(A, B); void getdata( int n) friend int sum(A, B); int sum(A m, B n) int result; result = m.y + n.x; return result; cout << "The sum is : " << sum(a, b);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.
using namespace std; // Forward declaration void getdata( int n) friend int sum(A, B); void getdata( int m) friend int sum(A, B); int sum(A m, B n) int result; result = m.y + n.x; return result; cout << "The sum is : " << sum(a, b); 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.
Like Article -->Given a Binary search tree, the task is to implement forward iterator on it with the following functions. curr(): returns the pointer to current element.next(): iterates to the next smallest element in the Binary Search Tree.isEnd(): returns true if there no node left to traverse else false. Iterator traverses the BST in sorted order(increasing). W
7 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 memory and the ordering is maintained by associating ev
3 min read Set of List and Forward List in C++ with examplesSets Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. Functions used with Sets: begin(): Returns an iterator to the first
4 min read Forward List and List of Pairs in C++ with ExamplesForward List Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only
8 min read Forward List and List of Unordered Maps in C++ with ExamplesForward List Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only
10 min read Forward List and List of Tuples in C++ with ExamplesWhat is Forward List? Forward list in STL is used to implement a singly linked list. It was introduced from C++11 onwards, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list
9 min read Forward List in C++ | Set 2 (Manipulating Functions)Forward List in C++ | Set 1 (Introduction and Important Functions) More functions are discussed in this article Some of the operations other than insertions and deletions that can be used in forward lists are as follows : 1. merge() :- This function is used to merge one forward list with other. If both the lists are sorted then the resultant list r
5 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 types of iterators present in C++ Standard Library,
6 min read Forward List in C++ | Set 1 (Introduction and Important Functions)Forward list in STL implements singly linked list. Introduced from C++11, forward list are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the forward list keeps track of the location of only the next eleme
9 min read C++ Programming LanguageC++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read 30 OOPs Interview Questions and Answers (2024) UpdatedObject-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read C++ Programming ExamplesWriting C++ programs yourself is the best way to learn the C++ language. C++ programs are also asked in the interviews. This article covers the top practice problems for basic C++ programs on topics like control flow, patterns, and functions to complex ones like pointers, arrays, and strings. C++ Tutorial C++ Recent Articles Topics: Basic Programs
9 min read C++ Interview Questions and Answers (2024)C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read Introduction of Object Oriented ProgrammingAs the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of
6 min read Substring in C++The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is <string>. The substring function takes two values pos and len as an argument
8 min read Inheritance in C++The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read C++ PolymorphismThe word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read C++ Classes and ObjectsIn C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read Decision Making in C (if , if..else, Nested if, if-else-if )The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read C++ Data TypesAll variables use data type during declaration to restrict the type of data to be stored. Therefore, we can say that data types are used to tell the variables the type of data they can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared. Every data type
10 min read Convert String to int in C++Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read Priority Queue in C++ Standard Template Library (STL)A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read Map in C++ Standard Template Library (STL)Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read Object Oriented Programming in C++Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read Operator Overloading in C++in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
8 min read Templates in C++ with ExamplesA template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read Friend Class and Function in C++A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read Constructors in C++Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read Bitwise Operators in CIn C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two n