Help | Site Map
Connecting Tech Pros Worldwide
 
 
LinkBack Thread Tools
  #1  
Old July 7th, 2008, 05:15 PM
Dan Smithers
Guest
 
Posts: n/a
Default private member functions as friends

Can a make a private member function a friend? The code below suggests
not. I am using g++ 4.2.3

I realise that I can make the whole CFriend class a friend, or make my
friend function public but I don't really want to do either.

thanks

dan


#include <iostream>

class CClass;

class CFriend
{
private:
CClass& my_target;
void myWork(void);
public:
CFriend(CClass& target):my_target(target){;}
virtual ~CFriend(void){;}

void work(void){return myWork();}
};

class CClass
{
private:
void doWork(void)
{
std::cout << " CClass doWork() my_val = " << my_val++ << std::endl;
}

int my_val;

public:
CClass(int val):my_val(val){;}
virtual ~CClass(void){;}

friend void CFriend::myWork(void);
};

void
CFriend::myWork(void)
{
my_target.doWork();
}

int
main(int argc, char *argv[])
{
CClass first(1);

CFriend second(first);

second.work();
}
  #2  
Old July 7th, 2008, 05:45 PM
puzzlecracker
Guest
 
Posts: n/a
Default Re: private member functions as friends

On Jul 7, 12:05 pm, Dan Smithers <d...@foo.netwrote:
Quote:
Can a make a private member function a friend? The code below suggests
not. I am using g++ 4.2.3
>
I realise that I can make the whole CFriend class a friend, or make my
friend function public but I don't really want to do either.
>
thanks
>
dan
>
#include <iostream>
>
class CClass;
>
class CFriend
{
private:
CClass& my_target;
void myWork(void);
public:
CFriend(CClass& target):my_target(target){;}
virtual ~CFriend(void){;}
>
void work(void){return myWork();}
>
};
>
class CClass
{
private:
void doWork(void)
{
std::cout << " CClass doWork() my_val = " << my_val++ << std::endl;
}
>
int my_val;
>
public:
CClass(int val):my_val(val){;}
virtual ~CClass(void){;}
>
friend void CFriend::myWork(void);
>
};
>
void
CFriend::myWork(void)
{
my_target.doWork();
>
}
>
int
main(int argc, char *argv[])
{
CClass first(1);
>
CFriend second(first);
>
second.work();
>
}
Member functions cannot be friends. Only classes or user-defined
functions can be used as friends.

 

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over network members.
Post your question now . . .
It's fast and it's free

Popular Articles