venkysmarty
venkysmarty

Reputation: 11431

forward declaration and cyclic header inclusion in C++

I have two classes

RequestManager.h

#ifndef REQUESTMANAGER_H
#define REQUESTMANAGER_H

#include "RequestClient.h"
class RequestManager
{
public:
     void AddReqeustItem(RequestClient *req);

private:
 std::list<RequestClient*> m_reqClientContainer;
};
#endif

RequestClient.h

#ifndef REQUESTCLIENT_H
#define REQUESTCLIENT_H

class RequestManager; // Forward declaration to avoid cyclic inclusion.

class RequestClient {
public:
void CreateRequest(RequestManager* pManager)
{
  // ... I am creating a request.
  pManager->AddReqeustItem(req);
};
#endif

In the code above I am getting error undefined RequestManager in Request client class. What is the problem and how can I solve it?

Upvotes: 1

Views: 227

Answers (3)

Olaf Dietsche
Olaf Dietsche

Reputation: 74028

You use the method RequestManager::AddReqeustItem(), but there's only a forward declaration of RequestManager. With just a forward declaration the compiler doesn't even know which methods of RequestManager exist. So, to fix this problem, you must provide the definition of RequestManager, which is usually in the header file.

Move the method definition of CreateRequest() into the cpp file and include RequestManager.h there

RequestManager.cpp:

#include "RequestManager.h"
...
void CreateRequest(RequestManager* pManager)
{
  // ... I am creating a request.
  pManger->AddReqeustItem( req);
}

Upvotes: 1

Walter
Walter

Reputation: 45424

put the member function definition in a source file which #includes both headers.

Or, if you still want it to be inline (or if it's templated), then put the definition of the member function body further in the header, after all relevant code is defined. In the case of a single header file (which does make sense here):

class B; // forward decl
class A {
  void use(B*);
};

class B {
  void use(A*);
};

void A::use(B*b) { /* ... */ }
void B::use(A*a) { /* ... */ }

Note the splitting of the code into files (several headers and one source) is only a convenience for the programmer (making it much simpler to maintain and use by other parts of the code), but from the point of view of the compiler this doesn't matter: it sees only one big file of code (after pre-processing). So, it's up to you how you split the above layout into headers and source file.

Upvotes: 1

Patrice Bernassola
Patrice Bernassola

Reputation: 14426

You cannot use a type with only a forward declaration. Forward declaration are used to say to compiler that type exists but compiler does not know the content of the type.

My advice:

  • In header file, I would only define class and function members. So forward declaration is possible if only pointer are used.
  • In body file, write the code your member function and include the header files

Upvotes: 5

Related Questions