hisham
hisham

Reputation: 215

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:

ERRORS:

 model.h : error: invalid use of incomplete type 'class fileio'
 friend void fileio::read_boundary();

 model.h : error: forward declaration of 'class fileio'
 class fileio; 

 modell.h : In member function 'void fileio::read_boundary()':

 cmodel.h : error: 'std::vector<element> model::m_elements' is private
 std::vector<element>m_elements;

 fileio.cpp: error: within this context
 for(auto iter:m_model->m_elements)

EDIT:
Without forward declaration of class model in the fileio.h gives 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*'

If I comment out the friend function declaration and its definition, then the program will run without errors. How do I solve it?

Upvotes: 2

Views: 283

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93364

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

Upvotes: 2

Related Questions