devxlogo

Forward Declaring Classes

Forward Declaring Classes

Question:
I wrote:

 class Adjective {   Sentence adjective_sentence; };   class Noun {   Adjective a; };   class NounPhrase {   Noun n; };   class Sentence {   NounPhrase np; };  

Of course it doesn’t work, because I try to create an object before its class is defined. The opposite order (Sentence-NounPhrase-Noun-Adjective) also doesn’t work now because in Sentence I declare a nounphrase object.

It must be a simple problem to solve, because I tried this in Java and worked perfectly.

Answer:
Instead of creating complete objects as data members, forward declare all classes, and then use pointers or references as data members:

class Sentence; // fwd declarationclass Noun; // ditto class Adjective {   Sentence * padjective_sentence; //fine };   class Noun {   Adjective & radj; // reference, also fine };   class NounPhrase {   Noun * pnoun; };

]

In a separate .cpp file, where the member functions of these classes are defined, you can allocate the object members dynamically and assign their address to the pointers or references:

#include "sentence.h"#include "adjective.h"#include "noun.h"#include "nounphrase.h"Adjective::Adjective {   padjective_sentence new Sentence;  }Adjective::~Adjective {   delete padjective_sentence;}

See also  5 Ways to Improve Customer Experience
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist