By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,948 Members | 1,573 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,948 IT Pros & Developers. It's quick & easy.

private member functions as friends

P: n/a
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();
}
Jul 7 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On Jul 7, 12:05 pm, Dan Smithers <d...@foo.netwrote:
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.

Jul 7 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.