S
subramanian100in
The following post is for learning purpose only. I will try to avoid
friend functions and friend classes.
Consider the following piece of code:
class Test;
class Sample
{
public:
void friend_fn(const Test& ref);
// rest of the Sample class
};
class Test
{
public:
friend void Sample::friend_fn(const Test& ref);
// rest of the Test class
};
First approach:
We should structure the two class definitions only in the above
order(ie first the forward declaration of class Test followed by the
definition of class Sample and then the definition of class Test). Am
I correct ? If the two class definitions are kept in the above order
in the same header file, then there is no issue. But is it correct to
keep multiple class definitions in the same header file?
Now consider the following second approach:
Suppose I want to keep the definition of class Sample in, say,
Sample.h and the definition of class Test in Test.h. Also, suppose I
want to keep the function Sample::friend_fn() as an inline function.
Then the definition of Sample::friend_fn() should appear in Sample.h.
But the problem in this approach is that Sample::friend_fn() is going
to use some members of the class Test and we can only have a forward
declaration of class Test in Sample.h. My question: is this second
approach feasible ? If so, how to accomplish it ?
In real work environment, which approach is followed ? Kindly explain.
Thanks
V.Subramanian
friend functions and friend classes.
Consider the following piece of code:
class Test;
class Sample
{
public:
void friend_fn(const Test& ref);
// rest of the Sample class
};
class Test
{
public:
friend void Sample::friend_fn(const Test& ref);
// rest of the Test class
};
First approach:
We should structure the two class definitions only in the above
order(ie first the forward declaration of class Test followed by the
definition of class Sample and then the definition of class Test). Am
I correct ? If the two class definitions are kept in the above order
in the same header file, then there is no issue. But is it correct to
keep multiple class definitions in the same header file?
Now consider the following second approach:
Suppose I want to keep the definition of class Sample in, say,
Sample.h and the definition of class Test in Test.h. Also, suppose I
want to keep the function Sample::friend_fn() as an inline function.
Then the definition of Sample::friend_fn() should appear in Sample.h.
But the problem in this approach is that Sample::friend_fn() is going
to use some members of the class Test and we can only have a forward
declaration of class Test in Sample.h. My question: is this second
approach feasible ? If so, how to accomplish it ?
In real work environment, which approach is followed ? Kindly explain.
Thanks
V.Subramanian