Jump to content
  • Advertisement

Archived

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

Arch_Spider

classes

This topic is 6106 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!