When you make a class the friend of another class, is it required to use a prototype to access its members?

When a class has been declared as a friend in another class, does the friend class have to have a prototype in order for the other class to use to access its private and public members?

Please see below to understand what I mean

The Plants class has access to the private members in Color class. But is it required to use a prototype (that was declared in the Colors class) and define it in the plants class in order to access the members in Colors?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Plants class
#include <iostream>
#include "Color.cpp"

using namespace std;


class Plants
{
    string plantName;
    friend class Color;        //Color class is now a friend of plants class

public:

}object;

void Color::setMembers ()    //defining function that was declared by the prototype in color class
{
    black = "idc what you say, black is a color";
    cout << black;
}


int main ()
{
    object1.setMembers ();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//Color class
#include <iostream>
#ifndef COLOR_CPP
#define COLOR_CPP

using namespace std;

class Plants;

class Color
{
    string black;
	string white;

public:

	void setMembers ();        //do I have to use a prototype declared here in order for the plants class to access the private members in color?

}object1;




#endif




Last edited on
The Plants class has access to the private members in Color class.

In that case you want Plants to be a friend of Color and not the other way around as you have it now.

#include "Color.cpp"

Don't include .cpp files. Only include header files.
Last edited on
You have friendship backwards. You give colours a full access to plants.

Other notes:
* Do not name headers with .cpp. While you could use any filenames, most tools (particularly IDEs) expect convention that .cpp is a source file.

* Do not use global variables, unless necessary. Global variable defined in a header is definitely a bad idea.

* class Foo {} bar; is same as
1
2
3
class Foo {};

Foo bar;

It is less confusing, when type definition is separate from the variable declaration(s).
Ah I see, thank you for your response.

So when a friend class is declared inside another class, both classes have access to each others members right?
No. friend declaration means "I give this class rights to touch my private parts". Not "I can touch your private parts whenever I want because I thinky you are my friend"
Topic archived. No new replies allowed.