using instance of a class as a class variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • drsmooth
    New Member
    • Oct 2007
    • 112

    using instance of a class as a class variable

    I have a civilian class and i want it to have a member variable of type Job.

    i made the Job class, included it in the civilian header as such:

    Code:
    //--methods involved in working
       void giveJob(Job);
       void advanceTask();
       Job j;
    then i get this error before the consturctor in the cpp file:

    [C++ Error] Civilian.cpp(21 ): E2279 Cannot find default constructor to initialize member 'Civilian::j'

    i assume the compiler is assuming to instantiate the Job object but i do not want it too, do i have to just make a default constructor?

    thanks,
    ken
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    Unless you want to make your Job into a Job* and initialize it in your civilian constructor, you will have to provide a default constructor in your Job class (or provide default arguments for any pre-existing constructor).

    Comment

    • drsmooth
      New Member
      • Oct 2007
      • 112

      #3
      ok, if i set up a default constructor with no parameters and then later assign a Job class over it, does that work the same way?


      thanks
      ken

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Why not try it and see if it works?

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          You have this situation:
          [code=c]
          class Job
          {
          Civilian obj;
          };
          [/code]

          When you:
          [code=cpp]
          Job j;
          [/code]

          the compiler will
          1) allocate memory for the Job object
          2) call the Civilian default contstructor (the one you don't have)
          3) call the Job default constructor.

          Note that you don't need a Job default constrcutor because Job does not have any other constructors that you have written but Civilian does need a default constructor ottherwise the compile can't be sure that the Civilian member was properly initialized.

          Comment

          Working...