0

I have a classes that contains data in form of MyObjects like class A. I wish to Monitor the data in the MyObject objects. So I created a IMonitorable class and derived all my storage classes that contains the MyObjects from IMonitorable. Add added the IMonitorable class as a friend to my monitoring class.

class IMonitorable
{}        

class a : public IMonitorable
{
protected:
   struct myData
   {
      MyObject a;
      MyObject b;
      ...
   } data;
}

class Monitor
{
public:
   friend IMonitorable;
   AddData(a& stroage);
   AddObject(MyObject& obj);

}

This worked fine while I had one storage class with a known myData struct. I called

AddData(InstanceOfA);

and added MyObject a,b,.. to my monitoring mechanism.

Now I have several storage classes and I don't want to write an AddData method for all storage classes. I thought of having a AddObject method to be able to have a single point suitable for all storage classes.

AddObject(InstanceOfA.data.a);
AddObject(InstanceOfA.data.b);
...

But if I call this somewhere in my code gcc throws the error data.a is protected, what is right.

Is there a way to add a reference or a pointer of the protected MyObject to the Monitor without the knowledge of the structure of the storage class?

Steve
  • 1,072
  • 11
  • 28
  • 1
    Friends are not inherited in C++. See: http://stackoverflow.com/questions/7371087/c-friend-inheritance – Mark Garcia Oct 22 '12 at 09:00
  • The question is quite confusing. Take the time to check the code, and identify the meaning of some of the terms you use, like *storage*. Make sure to identify what object is trying to access what other object, what the error is and where it happens. – David Rodríguez - dribeas Oct 22 '12 at 12:10

2 Answers2

1

You declared struct myData as protected. friend IMonitorable declare IMonitorable as friend class that means that IMonitorable has acces to private members of Monitor class. To access private members from Monitor use getter function:

class a : public IMonitorable
{
public:
   const myData* const getData()const
   {
      return &data;
   }
   myData* getData()
   {
      return &data;
   }
protected:
   struct myData
   {
      MyObject a;
      MyObject b;
      ...
   } data;
}

Use it:

AddObject(InstanceOfA.getData()->a);
Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
1

I can't see exactly what you are doing, and you confuse things by using a both as a class and then a member of myData.

But I think the issue is that that friendship is not reciprocated.

You have made IMonitorable a friend of Monitor, but that does not make Monitor a friend of IMonitorable, and incidentally even if you did make it a friend of IMonitorable it wouldn't get access to protected members of a which derives from it.

CashCow
  • 30,981
  • 5
  • 61
  • 92