• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

Class Initialization?

I am given the a Person.h file which describes a Person.  At the top of the file there is a class initialized like so:

#include <string>

using namespace std;

class Job;

class Person {...}

Why does the line "class Job;" appear at the top?
0
323k13l
Asked:
323k13l
  • 3
  • 2
1 Solution
 
ikeworkCommented:
it is a forward declaration. it tells the compiler, that a class Job exists and it will be declared later.
this way you can use a pointer to class Job and a reference to it inside the header without actually include the header-file where the class Job is declared ..

ike
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi 323k13l,

This is called a "forward reference".  Somewhere in the class Person, there is probably a reference to a class called Job.  If class Job isn't declared, using it in class Person is a compilation error.

This technique allows you to declare a class (Job) and use it in another class (Person).  Then also use the second class (Person) in the first class (Job).

class Job;

class Person
{
  private Job MyJob;
};

class Job
{
  private Person Me;
};


Good Luck,
Kent
0
 
ikeworkCommented:
>> This technique allows you to declare a class (Job) and use it in another class (Person).  Then also use the second class (Person) in the first class (Job).

hi kent .. it only allows to use pointers or references, but not objects as in your example

class Job;

class Person
{
    void test( Job &j ) {}  // << reference is legal

    Job *pMyJob; // << pointer is legal

    Job MyJob;  // objects are NOT legal ..
};


ike
0
 
Kent OlsenData Warehouse Architect / DBACommented:
Hi ikework,

Yeah.  i'd just gotten back from lunch and saw that the question was unanswered so I threw one together and didn't proofread it before posting.


Thanks for cleanning up,
Kent
0
 
ikeworkCommented:
@kent .. c'est la vie ..  :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now