How do I create two classes that refer to each other in different header files?

Viewed 74

I have two classes in two different header files. I, as advised in another topic with a similar question, declared class A before class B and declared class B before class A. But it did not help. Seller still can't see the Organization

Seller.h

#ifndef OOP_3_SELLER_H
#define OOP_3_SELLER_H
#include "Organization.h"
class Organization;
class Seller{
protected:
Organization*owner;
...
};

Organiztion.h

#ifndef ORGANIZATION_OOP3_H
#define ORGANIZATION_OOP3_H
#include "Seller.h"
class Seller;
class Organization{
 std::vector<Seller*> own;
...
};

The compiler tells me the following error: error C2027: use of undefined type 'Organization'. That is, as I understand it, the Organization sees the Seller, but the Seller does not see the Srganization

1 Answers

Since you've forward declared the class Organization in Seller.h there is no need to write #include "Organisation.h". Similarly, in Organization.h" since you've forward declared class Seller there is no need to write #include "Seller.h". Also, always take into account cyclic dependency like in your program Organization.h has a #include "Seller.h" and then Seller.h has a #include "Organization.h"

The running(successfully compiled) program can be seen here.

Organization.h

#ifndef ORGANIZATION_OOP3_H
#define ORGANIZATION_OOP3_H
//#include "Seller.h"
#include <vector>
class Seller;
class Organization{
 std::vector<Seller*> own;

};
#endif

Seller.h

#ifndef OOP_3_SELLER_H
#define OOP_3_SELLER_H
//#include "Organization.h"
class Organization;
class Seller{
protected:
Organization*owner;

};
#endif

In the .cpp files(also called source files) you should include the headers using #include.

Your program has other problems too like many(and i mean many many)of the methods in Seller.h have no return value for methods that have non-void return type.

I tried solving some of the problems in you github code but there are just too many problems(errors and warnings) to solve. Also i would suggest you to use cpp files as well.

Related