Archived

This topic is now archived and is closed to further replies.

Arch_Spider

classes

Recommended Posts

hi there, I have two classes. I want it to be possible that class1 can use some methods in class2, which the object can not access. I can let class1 inherit class2 and use the keyword protected, but are there other ways to accomplish this. Does anyone has a suggestion? thanks.

Share this post


Link to post
Share on other sites
Assuming you''re using C++, you can use the ''friend'' storage class. I don''t know how, though, I''ve never used it. A quick search on www.google.com should find some stuff about it.

All your bases belong to us

Share this post


Link to post
Share on other sites
A friend function is not a member function of a class, but an ordinary function that has acces to private members of that class.

Example:
// here My_Class would be class2 in your example, just add
// your friend functions and other classes can acces private
// variables of this class
class My_Class
{
Public:
// it doesn´t matter if you put the declaration in the
// public or private section because it is always
// public. We put it here for clarity
friend bool CheckIfEqual(My_Class value1, My_Class value2);
// put member functions here
.
.
.
Private:
int number1;
};

// definition of the friend function. Returns true if number1 are equal in instances of My_Class.
bool CheckIfEqual(My_Class value1, My_Class value2)
{
return (value1.number1 == value2.number1);
}


This is just a example but you should get the point.

Share this post


Link to post
Share on other sites
Classes can have other classes as friends too (not just functions).

e.g.
  
class Foo
{
//....

friend class Bar;
//....

};

class Bar
{
//....

};

Remember that friends can not be inherited.

Share this post


Link to post
Share on other sites
Ah, I see. Would this be possible:
  
friend bool Class2::CheckIfEqual(My_Class value1, My_Class value2);


Never mind, looks like Dactylos answered that for me.

All your bases belong to us

Share this post


Link to post
Share on other sites