Friends and Namespaces

S

Simon

Hi,

I have a class Foo which defines a friend function Bar. When I place the Bar
function within a namespace, I can no longer access the Foo private data
(i'm guessing it is not recognised as a friend). Could someone explain this
behaviour, as i'm obviously not understanding namespaces properly.

Thanks for your help,
Simon ;o)

//---------------

#include <iostream>

class Foo {
public:
Foo() { foo_int = 101; }
private:
int foo_int;
friend Bar(const Foo& f);
};

namespace mynamespace {
int Bar(const Foo& f) {
return f.foo_int;
}
}

int main() {
Foo f;
std::cout << mynamespace::Bar(f);
return 0;
}
 
W

WW

Simon said:
Hi,

I have a class Foo which defines a friend function Bar. When I place
the Bar function within a namespace, I can no longer access the Foo
private data (i'm guessing it is not recognised as a friend). Could
someone explain this behaviour, as i'm obviously not understanding
namespaces properly. [SNIP]
class Foo {
public:
Foo() { foo_int = 101; }
private:
int foo_int;
friend Bar(const Foo& f);

friend mynamespace::Bar(const Foo& f);
};

namespace mynamespace {
int Bar(const Foo& f) {
[SNIP]

Bar is not called Bar anymore. It is mynamespace::Bar. With your original
libe you gave friendship to a function called Bar, in the global namespace.
 
T

tom_usenet

Hi,

I have a class Foo which defines a friend function Bar. When I place the Bar
function within a namespace, I can no longer access the Foo private data
(i'm guessing it is not recognised as a friend). Could someone explain this
behaviour, as i'm obviously not understanding namespaces properly.

You have to declare friendship to the function in the namespace, not
to a non-existent global one.
Thanks for your help,
Simon ;o)

//---------------

#include <iostream>

class Foo;

namespace mynamespace {
int Bar(const Foo& f);
}
class Foo {
public:
Foo() { foo_int = 101; }
private:
int foo_int;
friend Bar(const Foo& f);

friend mynamespace::Bar(const Foo& f);

};

namespace mynamespace {
int Bar(const Foo& f) {
return f.foo_int;
}
}

int main() {
Foo f;
std::cout << mynamespace::Bar(f);
return 0;
}

Tom
 
J

Jonathan Mcdougall

I have a class Foo which defines a friend function Bar. When I place
friend mynamespace::Bar(const Foo& f);

Just to be accurate, you'll get a bunch of errors since
1) mynamespace is undeclared at this point
2) the Bar declaration has no return value

class Foo;

namespace mynamespace
{
int Bar(const Foo& f);
}

class Foo
{
..
friend int mynamespace::Bar(const Foo &f);
};

...


Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top