Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jul 25, 2000

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 declaration
class 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;
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date