Is it OK to specify a _private_ member function as a friend?

R

Risto Lankinen

Hi!

Should this compile:

class C
{
private:
void f();
};

class D
{
friend void C::f(); // <- "line 10"
};

int main()
{
return 0;
}

It compiles fine with many compilers, but one compiler rejects
it with the following error:

"test.cpp", line 10: Error: #265-D: function "C::f" is inaccessible

The explanation provided by the error message borders with
reasonable (since C::f after all is a private function, and hence
should be inaddressable by anyone else). Now I'm in doubt
whether this is a bug in said compiler, or if it is an exception
in the access control mechanism. I'm leaning towards a bug
in this compiler since so many others accept it, but then again,
a million flies can't be wrong... :)

What does the standard say, anyway?

Cheers!

- Risto -
 
D

Dan W.

Hi!

Should this compile:

class C
{
private:
void f();
};

class D
{
friend void C::f(); // <- "line 10"
};

int main()
{
return 0;
}

It compiles fine with many compilers, but one compiler rejects
it with the following error:

"test.cpp", line 10: Error: #265-D: function "C::f" is inaccessible

The explanation provided by the error message borders with
reasonable (since C::f after all is a private function, and hence
should be inaddressable by anyone else). Now I'm in doubt
whether this is a bug in said compiler, or if it is an exception
in the access control mechanism. I'm leaning towards a bug
in this compiler since so many others accept it, but then again,
a million flies can't be wrong... :)

What does the standard say, anyway?

Cheers!

- Risto -
When you declare anything "friend", it means that you're giving it
permission to access you, NOT giving yourself permission to access it.
If you want class D to access a private function of class C, class C
must declare class D friend, or, preferably, just the function of
class D that needs to call C::f().
 

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,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top