Search code examples
c++friend-functionnon-member-functions

How to declare a function returning a class instance, that is used in the same class?


I've tried couple of weeks and searched for days for an answer, but haven't found it. My code is rather large and intertwined, but my problem is with 3 functions/classes, therefore I will only show my declarations and relevant information. I have the following non-compliable code:

class Word{
private:
*members*
public:
  //friend declaration so i could access members and use it in class - doesn't help
  friend Word search_in_file(const string& searchee);

  //function that uses previous function to create a Word object using data from file:
  //type int to show it succeeded or failed
  int fill(const string& searchee){
     Word transmission = search_in_file(searchee);
     //here are member transactions for this->members=transmission.member;
}

};

//function to return Word class from file:
Word search_in_file(const string& searchee){
//code for doing that
}

I've tried every possibility where I could declare the functions or class and haven't found a solution. At first I only used the search_in_file() function in the constructor(which now has the same problem as the function fill() ) and declared and defined the search_in_file() function in the class. Then it worked as above code (with the only exception being the friend function was the actual function with definition as well). But I need to use the function without having a Word object declared and therefore it needs to be outside of the class. How can I make it work?

I should also point out that I have another non-member function that uses Word as a parameter, and that function works with the above solution. Although it has on overloaded version, that doesn't use Word as parameter declared before the class and I think that is why it works.


Solution

  • You want this:

    #include <string>
    
    using namespace std;
    
    // declare that the class exists
    class Word;
    
    // Declare the function   
    Word search_in_file(const string& searchee);
    
    class Word {
    private:
      
    public:
      //friend declaration so i could access members and use it in class - doesn't help
      friend Word search_in_file(const string& searchee);
    
      //function that uses previous function to create a Word object using data from file:
      //type int to show it succeeded or failed
      int fill(const string& searchee) {
        Word transmission = search_in_file(searchee);
        //here are member transactions for this->members=transmission.member;
      }
    
    };
    
    // Now class Word is completely defined and you can implement the function
    
    Word search_in_file(const string& searchee)
    {
      //...
    }