user7491077 user7491077 - 4 years ago 117
C++ Question

iterating through private member of another class using friend function

I have declared a friend function inside the below class.

Class model

#include "fileio.h"
class fileio;
class model
{
std::vector<element>m_elements;
public:
friend void fileio::element_iterator();
}


element_iterator()
is a public function of the
class fileio
.

Class fileio

#include "model.h"
class model;
class fileio
{
model* m_model;
public:
fileio(model*);
void element_iterator();
}


The
element_iterator()
function is defined as below.

void fileio::element_iterator()
{
for(auto &iter : m_model->m_elements)
{
//some functions
}
}


I want to iterate through the
m_elements
from another class using friend function. But I'm getting errors as below:

error: invalid use of incomplete type 'class fileio'


error: forward declaration of 'class fileio'
.

EDIT:

As suggested in the comment, I added
#include "fileio.h"
in the
class model
. But it gave another set of errors as below:

error: 'model' has not been declared
fileio(model*);

error: 'model' does not name a type
model* m_model;

candidates are:
fileio::fileio(int*)
fileio(model*);
no known conversion for argument 2 from 'model*' to 'int*'


So the error is seemingly in the constructor of
fileio class
. If I comment out the friend function declaration and its definition, then the program will run without errors.
How do I solve it?

Answer Source

Instead of forward-declaring fileio in model.h, include its full definition.

// fileio.h
class model;
class fileio
{
    model* m_model;
    public:
    void element_iterator();
};

// model.h
#include "fileio.h"
class model
{
    std::vector<int >m_elements;
    public:
    friend void fileio::element_iterator();
};

wandbox example


Alternatively, you could make the entire fileio class a friend - this would allow you to use its forward-declaration, which might be what you want depending on your real situation.

// model.h
class fileio;
class model
{
    std::vector<int >m_elements;
    public:
    friend class fileio;
};

// fileio.h
class model;
class fileio
{
    model* m_model;
    public:
    void element_iterator();
};

wandbox example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download