I am getting the following error:
'class name' does not name a type
for all of my classes.
I suspect it may be a circular dependency but I have no clue how to solve it as each class requires access to a function from the next. Below are my classes:
Container.h:
#ifndef CONTAINER_H
#define CONTAINER_H
#include "Factory.h"
class Container
{
public:
Container()
{
array = new int[10];
for (int i = 0; i < 10; ++i) {
array[i] = i;
}
}
Iterator* createIterator()
{
Factory fac;
return fac.factoryMethod();
}
friend class Iterator;
private:
int* array;
};
#endif //CONTAINER_H
Factory.h:
#ifndef FACTORY_H
#define FACTORY_H
#include "Iterator.h";
class Factory
{
Iterator* factoryMethod(Container* con)
{
return new Iterator(con);
}
};
#endif //FACTORY_H
Iterator.h:
#ifndef ITERATOR_H
#define ITERATOR_H
#include "Container.h"
class Iterator
{
public:
Iterator(Container* con)
{
this->con =con;
}
int getFromIndex(int i)
{
return con->array[i];
}
private:
Container* con;
};
#endif //ITERATOR_H
main.cpp:
#include <iostream>
using namespace std;
#include "Container.h"
#include "Iterator.h"
int main() {
Container con;
Iterator* it = con.createIterator();
cout<<it->getFromIndex(2)<<endl;
return 0;
}
Thank you in advance for any help.
It is indeed a circular dependency between your headers. Container.h
includes Factory.h
, which includes Iterator.h
, which includes Container.h
.
The solution is to move the implementations of member functions from header files into source files. That way, header files will only need declarations, not definitions, of the classes, which you can easily put directly in the "consuming" header files:
class Iterator;
class Container
{
public:
Container();
Iterator* createIterator();
friend class Iterator;
private:
int* array;
};
Then, in an appropriate source file (such as Container.cpp
), implement the member functions and include any headers you need:
Container.cpp
#include "Container.h"
#include "Factory.h"
Container::Container() : array(new int[10])
{
for (int i = 0; i < 10; ++i) {
array[i] = i;
}
}
Iterator* Container::createIterator()
{
Factory fac;
return fac.factoryMethod();
}
(Dtto for Factory
and Iterator
, of course).
Don't forget to link all the source files together when building your final binary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With