lukica
lukica

Reputation: 15

<Base> must be a previously defined class or struct

I have a header and cpp file for a base class, and a header and cpp file for a derived class. I am getting the below error in the header file of the derived class:

Base must be a previously defined class or struct.

I have included the base class header file in the derived class header file. I realize that the definition of the base class isn't in the header file, but I read that including a cpp file isn't a good practice. Also, if I put both class definitions in same header file and implement both classes in the same cpp file, there's no errors.

Since the code is for a school project, I will give the example, but not the exact code:

base.h

#ifndef _base_h_
#define _base_h_

#include "derived.h"

class Base {
public:

  void start();
  void waitToComplete();
  virtual ~Base();

  static void sleep(Time timeToSleep);

protected:

  friend class Derived;
  Base ();
  virtual void run() {}
};

#endif

derived.h

#ifndef _derived_h_
#define _derived_h_

#include "base.h"

class Derived : public Base{
public:
  Derived();
  void run();
  void start();
  ~Derived() ;
};
#endif

Upvotes: 0

Views: 407

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

This is a typical circular dependency. The Base class doesn't need the full definition of Derived, only know that it exists. This is done through forward declarations.

With a proper forward declaration, the base.h header file doesn't need to include the derived.h header file:

//File: base.h
#ifndef _base_h_
#define _base_h_

// Do not include header file for Derived
// Only do forward declaration
class Derived;    

class Base {
public:

void start();
void waitToComplete();
virtual ~Base();

static void sleep(Time timeToSleep);

protected:

friend class Derived;
Base ();
virtual void run() {}
};

#endif

On a couple of unrelated notes:

  • The Base::run function should probably be a pure virtual function:

    virtual void run() = 0;
    
  • Should the Derived class really override the start function?

  • If you're overriding functions in a derived class, you should use the override special modifier identifier:

    void run() override;
    

Upvotes: 3

Related Questions