Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

friend question

Status
Not open for further replies.

swingkyd

Programmer
Jul 10, 2003
34
CA
I would reallly appreciate some help with this. The actual code is different, but the setup is the same...

I have created two classes:
Class1, Class2
each in separate header files.
i've created #ifndef declarations for both and included the header files of each class.

for some reason, the "friend" declaration doesn't want to let me access any member functions of the other class:

I've also prototyped each class in the other class definition.

Class1.h excerpt:
Code:
friend class Class2;
void dosomething();[\code]
...
[code]Class1::dosomething(){
cout<<&quot;made it!\n&quot;;
}[\code]

Class2.h excerpt:
[code]friend class Class1;
void accessfunction();[\code]
...
[code]Class2::accessfunction(){
dosomething(); // does not work... say's &quot;undefined identifier 'dosomething'&quot;
}[\code]

I'd really appreciate some help... this is simplified from my real code by I believe it's the same situation...

Am I missing what a &quot;friend&quot; does? is there something else I need to do to get it to recognize the member function?

thanks!
 
Since the code you posted is not real code it is difficult to say with certainty. However, since doSomething() is a member function of Class1 any code that is not member code of Class1 cannot call the function as a global function as you posted:
Code:
Class2::accessfunction(){
dosomething(); // does not work... say's &quot;undefined identifier 'dosomething'&quot;
}

This of course has nothing to do with friend semantics.


-pete
 
so what are the &quot;friend&quot; semantics.
I think it might be because they are separate objects and I have not created both &quot;Class1&quot; and &quot;Class2&quot; objects...Just &quot;Class2&quot;.

Here's why i thought i could do it:
from a c++ tutorial...
&quot;Just as we have the possibility to define a friend function, we can define a class as friend of another one allowing that the second one access to the protected and private members of the first one.&quot;

I think I should change my friend declaration to something else... any ideas?
 
Code:
// forward declaration
class Class2;	// Class2 header file not needed for friend keyword
class ClassA{
	friend Class2;
private:
	void speak(){
		cout << &quot;This is ClassA speaking&quot; << endl;
	}
};

// ClassA.h include required
class Class2{
private:
	ClassA _classA;
public:
	void speakA(){
		_classA.speak();   // call private member since we are a friend
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	Class2 c;
	c.speakA();

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top