user14368465
user14368465

Reputation:

What's the purpose and meaning of this declaration

I have this code, I am looking at the code below, and I cannot figure out why on earth class Node; would be written and then again but with implementation.

class Doubly_Linked_List
{
   class Node; // <--- Why is this declared here??
   
   class Node : public Link {
        // Some Node code goes here.
   }
   
   Link head;
}

Upvotes: 0

Views: 101

Answers (1)

anatolyg
anatolyg

Reputation: 28320

Declarations like class Node; are forward declarations. They are sometimes useful if you want to do some basic operations with your class, which don't require a full declaration.


One example of such a basic operation is declaration of methods. Suppose you have a bunch of very important methods in your Doubly_Linked_List class, and you want their declarations near the top. Because some methods mention Node in their declaration, you need some kind of declaration for Node - a forward declaration is good because it doesn't distract you from the really important stuff - your methods.

To define your methods, you have to provide a definition for Node, but you do it later in code, which helps organize it in a logical way - most important stuff first.

class Doubly_Linked_List
{
public:
   class Node; // forward declaration
   int very_important_method_1(Node node1, Node node2);
   Node very_important_method_2();

   // a virtual code separator; all code below is less important

   class Node : public Link {
        // Some Node code goes here.
   }
   
private:
   Link head;
}

int Doubly_Linked_List::very_important_method_1(Node node1, Node node2)
{
   // code
}

Doubly_Linked_List::Node Doubly_Linked_List::very_important_method_2()
{
   // code
}

This is a niche technique; very rarely useful if you define your class shortly after you forward-declare it.


Forward declarations are usually useful when the definition of your class is in another file.

You can separate your code into two files, interface and implementation. Definition of Node doesn't belong in the interface file (*.h), but it's needed to declare parts of Doubly_Linked_List class. This is the classic use of forward declarations.

// Doubly_Linked_List.h
class Doubly_Linked_List
{
public:
   class Node;
   int very_important_method_1(Node node1, Node node2);
   Node very_important_method_2();
   
   Node* whatever; // pointers to incomplete type are allowed here
}
// Doubly_Linked_List.cpp
class Node : public Link {
    // Some Node code goes here.
}

int Doubly_Linked_List::very_important_method_1(Node node1, Node node2)
{
   // code
}

Doubly_Linked_List::Node Doubly_Linked_List::very_important_method_2()
{
   // code
}

Upvotes: 1

Related Questions