classes

Started by
3 comments, last by Arch_Spider 22 years, 5 months ago
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.
Advertisement
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
CoV
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.

Friðrik Ásmundsson
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.
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
CoV

This topic is closed to new replies.

Advertisement