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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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