Sc00by_d00
Sc00by_d00

Reputation: 65

How to deal with friend functions more appropriately?

Below is the String class I've created with a constructor and a copy constructor. I've declared a class M which contains function void print(String s); , then I tried to make function print of class M as the friend of class String but it gives compile time error saying M does not exists. On the other hand if I make class M the friend of class String surprisingly the code works.

#include<iostream>
#include<cstring>
using namespace std;
class String{
private:
    char* str;
    size_t len;
public:
    String(char* str){
        len=sizeof(str)/sizeof(char);
        this->str=new char[(int)len];
        strcpy(this->str,str);
    }
    String(const String& s){
        if(str!=s.str)
        {
            strcpy(str,s.str);
            len=s.len;
        }
    }
    friend void M::print(String);//This line gives compile time error saying M does not exists.
    // friend class M;//This line on the other hand works completely fine when uncommented
};
class M{
public:
    void print(String s){
        cout<<s.str;
    }
};
int main()
{
    char x[6]={'H','e','l','l','o','\0'};
    String str=x;
    M a;
    a.print(str);
    return 0;
}

Upvotes: 0

Views: 59

Answers (1)

user7860670
user7860670

Reputation: 37599

C++ behavior is rather inconsistent in this matter. Making class M a friend would be equivalent to forward declaring this class. However making a method of that class a friend would require that class to be defined:

class String;

class M{
public:
    void print(String s);
};

class String { 
 // definition goes here...
  friend void M::print(String); // now works because compiler is aware of M::print
};

void M::print(String s)
{
   cout<<s.str;
}

Upvotes: 2

Related Questions