Inheritance and protected members

Started by
2 comments, last by Matthew02 21 years, 5 months ago
Lets say that I have a class A with a private pointer to some data and a protected accessor for that data.
      
class A
{
    ...
protected:
    void * GetData() const { return m_Data; }

private:
    void * m_Data;
};
  
Then I have two derived classes B and C. Both have functions which take a reference to the other type.
  
class B
{
public:
    ...
    void SomeFunc(C& c);
}

class C
{
public:
    ...
    void SomeFunc(B& b);
}
  
I want to be able to use the derived accessor function for each type from within each function, but I don't want it to be available anywhere other than the base class or the derived classes.
  
void B::SomeFunc(C& c)
{
    void * Data = c.GetData();  // want to do this

}

void C::SomeFunc(B& b)
{
    void * Data = b.GetData();  // want to do this

}

void Func(B& b, C& b)
{
    void * Data = c.GetData();  // don't want to do this

    void * Data = b.GetData();  // don't want to do this

}
  
Obviously, I cannot do this the way that I was hoping with the protected accessor, but I don't want the accessor to be public. Is there anything else that I can do? Thanks for the help. -Matthew [edited by - matthew02 on October 30, 2002 10:37:15 AM]
Advertisement
Have you tried with "friend" ?


class B;

class A
{
friend B;
protected:
int getData();
private:
int m_iData;
};

class B
{
public:
int GetData(A &a);
};

or something (
Funny thing. I had the child classes friended to each other before, but I had a virtual accessor. The classes made different use of the member pointer. When I decided to use a single inherited accessor and just cast the pointer, I took out the friends. Now that you mentioned it, I put them back in and it worked. Thanks for your help.

-Matthew


[edited by - matthew02 on October 30, 2002 2:16:32 PM]
I was at a job interview once where the guy interviewing me asked what was the C++ keyword that allowed you to break the member hiding rules of a class. I wasn''t quite sure, I told him, and he said, "GOOD! I''m glad you don''t know it. The answer is ''friend''"

I was a bit embarasssed because I knew the keyword, but I wasn''t too familiar with it''s use. He went on with his explanation of why he shunned the keyword. "You can think of a class as a person. You have things that are public like your face and your hair that everyone can see and have access to. And you also have things that are private that only you have access to. HOWEVER. You do NOT want your FRIENDS touching your PRIVATES. If anything they should have made a keyword called ''spouse''."

There are certain instances where we need friend though, like if we want to hook some wicked inline assembly routines into our math library.


GOOD LUCK!

This topic is closed to new replies.

Advertisement