Archived

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

patindahat

Access to private/protected methods for ONE class

Recommended Posts

patindahat    118
I''m looking to have one class I create call come methods out of another class in the constructor/destructor. I want NOTHING else to call these methods, is there anyway to do this? I''m sure its something to do with the friend keyword, but I''ve never ventured with that part of C++. Pat - Ex nihilo nihilus

Share this post


Link to post
Share on other sites
Ready4Dis    180
Yes... make the variables protected, then inherit as a friend... I beleive that''s what you''re looking for:

class A
{
protected:
void Test();
};

class B : friend A
{
public:
CallTest() { Test(); }
};

Share this post


Link to post
Share on other sites
patindahat    118
Thank you, I just read threw my SAMS TYSC++ in 24 hours and friends is exactly what I want (including that derived classes aren''t friends)... BUT, my book shows nothing for syntax. And the class B:friend A returns a syntax error with MS VC++''s compiler. Any suggestions?

Pat - Ex nihilo nihilus

Share this post


Link to post
Share on other sites
SpaceRogue    122
class A
{
};

class B
{
friend class A;
};


Now A has access to all of B. Remember to put the friend statment in the class you want to access, not the one that needs access. Also, placing the statment in private, protected, or public sections will make no difference...it can go anywhere in the class definition.

[edited by - SpaceRogue on August 7, 2003 5:25:55 PM]

Share this post


Link to post
Share on other sites
patindahat    118
Here is basically what I''m trying to do.

class A
{
private:
unsigned m_Data;

protected:
virtual const A*AddData() { m_Data++; return this; }

virtual void RemoveData() { m_Data; }
};


class B
{
A *m_pA;
...
B(A &a)
};

B::B(A &a) { m_pA = a.AddData(); }
B::~B() { m_pA->RemoveData(); }


Now the actual methods which effect data do more than that, which is why I don''t want to directly access Data.

Pat - Ex nihilo nihilus

Share this post


Link to post
Share on other sites
patindahat    118
I did just as you did:

class B
{
friend A;
...
};

then when I try to call the AddData function on a referance passed object in the constructor I get an access violation error.

Pat - Ex nihilo nihilus

Share this post


Link to post
Share on other sites
EL    122
You have to reverse A and B.
Edit - few seconds too late

[edited by - EL on August 7, 2003 5:29:33 PM]

Share this post


Link to post
Share on other sites