'How to access private members in friend function in header class

I have created header file for definition of Class

Name.h

class Name
{

private:

    char* Fname;

    char* Lname;

public:

    Name(char* ='\0', char* ='\0');
    
    void setFname(char *);
    void setLname(char* );
    char* getFname();
    char* getLname();
    Name(Name& A);
    friend std::ostream& operator<<(std::ostream&, Name&);
    ~Name();
};

but while accessing private member in friend function it show that n.Fname is inaccessible..

Name.cpp

ostream& std::operator<<(std::ostream& out, Name& n) {
    
out << "Name: " << n.Fname;

}


Solution 1:[1]

The problem is that while implementing the overloaded operator<< you've used std::operator<< instead of just operator<<. This can be corrected by removing the qualification std:: as shown below.

Additionally, you're missing a return statement inside the definition of overloaded operator<<.

//------------v----------------------------------------->removed the std:: from here
std::ostream&  operator<<(std::ostream& out, Name& n) {
    
out << "Name: " << n.Fname;
return out; //added return statement
}

Also, note that typically the second parameter to the overloaded operator<< is a reference to const (const Name& in your case) so that the declaration would look like:

class Name {
//other members
   
//----------------------------------------------------vvvvv--------->const added here
        friend std::ostream& operator<<(std::ostream&,const Name&);

};
//-----------------------------------------vvvvv-------------->const added here
std::ostream& operator<<(std::ostream& out,const Name& n) {
    
out << "Name: " << n.Fname;
return out;
}

Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1