I am trying to make a friend function in a class definition that has access to the private members of another class definition, but so far the compiler keeps saying that it is unable to define the member function...
Below is the code that has the friend function, what am I doing wrong?
#include <iostream>
#include "Color.h"
usingnamespace std;
class Plants
{
staticint number_of_plants;
public:
staticint getNumber ();
friend string Color::getColor() //here is the friend function
{
black = "YUCK!!"; //private member of Color class
return black;
}
}object;
int Plants::number_of_plants = 0;
int main ()
{
cout << object.Color::getColor ();
}
And here is the class that the friend function is trying to access
It doesn't work that way. If you want a method from one class to have access to the privates of another class, that other class must declare your class as a friend.
(Helpful analogy: you can declare your kid a "friend" so he has a key to the house and may eat the food in the refrigerator. The guy two houses down cannot declare himself a friend and come demanding to see in the fridge.)
So do I just need to put the friend keyword next to the function that I want to use for another class definition? How can I make the other class declare a class as a friend?
Ahh I understand friend functions now. So friend functions are just functions that are not part of a class, but they have access to the private members of the class.
But i have a question, why is it that my program crashes right after displaying the private member in a friend function?
#include <iostream>
usingnamespace std;
class Plants
{
string plantName;
public:
friend Plants getMembers ();
}object;
Plants getMembers ()
{
object.plantName = "rose";
cout << object.plantName //if i try to display the value, the program will crash, why is that?
}
int main ()
{
getMembers ();
}
Is this code complete? I can't really tell but I think this has something to do with the fact that you return a Plants object which is missing in your code.
Also, friend is completely obsolete here IMO, pass objects instead.