Namespace friend functions C++

  • Context: C/C++ 
  • Thread starter Thread starter shwanky
  • Start date Start date
  • Tags Tags
    C++ Functions
Click For Summary
SUMMARY

The discussion addresses the implementation of friend functions in C++ that need to exist in multiple namespaces. The class Random requires a friend function sort to access its private members from both the ascending and descending namespaces. The proposed solution involves using forward declarations and pointers, allowing the friend function to be defined in each namespace while maintaining access to the class's private members. This method effectively resolves the circular dependency issue inherent in the original design.

PREREQUISITES
  • C++ programming language fundamentals
  • Understanding of namespaces in C++
  • Knowledge of friend functions and their access control
  • Experience with class design and member access in C++
NEXT STEPS
  • Explore C++ friend functions and their implications on encapsulation
  • Learn about forward declarations in C++ and their usage
  • Investigate the use of templates in C++ for function design
  • Study advanced namespace management in C++
USEFUL FOR

C++ developers, software engineers, and programmers interested in advanced class design and namespace management techniques.

shwanky
Messages
43
Reaction score
0
So I have this Class Random that needs to have a friend function sort which needs to exist in two namespaces.

Class Random
{
... Some stuff
friend void sort(Random &x);
}

namespace ascending
{
void sord(Random &x)
{
... Some Stuff
}
}

namespace descending
{
void sort(Random &x)
{
... Some Stuff
}
}


The problem is I need sort to be able to access the private members of the Random class but to define sort I need to have the namespaces ascending and descending already declared... Its a weird circular argument that can't work. My question is, how can I define the Class Random with so that it can have a friend function sort that resides in two namespaces?
 
Technology news on Phys.org
I think that you can do the following.

class Random;

namespace ascending
{
void sort(Random* x)
{
...
}
}

namespace descending
{
void sort(Random* x)
{
...
}
}

class Random
{
friend void ascending::sort(Random* x);
friend void descending::sort(Random* x);
...
};

I think that will work; however, I haven't tried it. You may also be able to do the same sort of thing using templates instead of the forward declaration and pointer usage.

Ken
 

Similar threads

  • · Replies 25 ·
Replies
25
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
89
Views
7K
  • · Replies 36 ·
2
Replies
36
Views
3K
Replies
20
Views
2K
  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 34 ·
2
Replies
34
Views
4K