CodeTrek
CodeTrek

Reputation: 475

Why does inline not work here?

Edit: Big Aplogies - I have had gTime declared after gUniverse but posted it here wrong after being asked to provide more code. I confused it with an earlier version of my program where actually it was opposite around.

I have a class gUniverse that contains a declaration of a a pointer to an instance of another object of the class gTime;

class gUniverse;
class gTime;

class gUniverse
    {
    public:
    gUniverse():UniverseTime(new gTime(1) ){}
    ~gUniverse();

    gTime* UniverseTime;
    };

class gTime
    {
  public:
    gTime();
    gTime(int start);
    void StartTimer();
    double ElapsedTime();

  private:
    clock_t StartTime;
    clock_t StopTime;
};

This does not compile with "incomplete type".

However, when I make an outside declaration, that is:

class gUniverse
    {
    public:
    gUniverse();
    ~gUniverse();

    gTime* UniverseTime;
    };

gUniverse::gUniverse():UniverseTime(new gTime(1) )
   {
   }

Then this is all cool now. I want to understand what's the problem and if the second case is okay to do, given that I take care of all destructors and copy constructors.

Upvotes: 0

Views: 158

Answers (1)

Aaron McDaid
Aaron McDaid

Reputation: 27133

This is the important expression:

new gTime(1)

This line of code cannot be compiled unless the compiler knows the interface to the gTime class. For example, it needs to see if it has a constructor that can accept an int or some other constructor that can take 1 as a single argument.

One solution is to move the entire gTime class nearer to the start of the file, above the gUniverse class.

Alternatively, you can move this new ... to later in the file, below gTime. You did this by moving that definition outside the class and into:

gUniverse::gUniverse():UniverseTime(new gTime(1) )    {   }

However this works only if you place it after the gTime class. If you had simply placed this after the gUniverse class and before the gTime class, then this wouldn't work. So this isn't really about inline versus external - the important thing is that this definition of the gUniverse constructor must be after the gTime class.

Upvotes: 1

Related Questions