Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve "Does not name a type" error

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.

like image 818
Keagansed Avatar asked Jan 06 '23 07:01

Keagansed


1 Answers

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.

like image 94
Angew is no longer proud of SO Avatar answered Jan 13 '23 15:01

Angew is no longer proud of SO