tags:

views:

45

answers:

3

Hello, I have such classes:

class Base
{
    private: bool mEnabled;
    public: bool getEnabled() { return mEnabled; }
};

class First : public Base;
{
  // ...
};

class Second : public Base
{
   Second() {
      // I have to check First::mEnabled
   }
};

class Manager
{
    First obj1;
    Second obj2;
};

I have some class manager which handles 2 another classes. And I have to check mEnabled variable in one such object from another. What's the right way? Would it be right if I'll make

static bool mEnabled;
static bool getEnabled();

p.s. There would be only 1 objects of this classes.

A: 

You can invoke member functions on certain objects by preceding the function's name with the object's name and a dot:

void f(First& first)
{
  if(first.getEnabled()) 
    ...
}

If you pass by pointer, use a -> instead of the .:

void f(First* first)
{
  if(first->getEnabled()) 
    ...
}
sbi
I don't have acces to the object of First class in the object of Second class.
Ockonal
@Ockonal, not clear on what you ask, but you could make the enabled of the Base class static, so that if it is set, you could check it by any object
@user384706 I asked about static in the post. I know how to make all of these. All I need is to know, isn`t it 'bad'.
Ockonal
Could you use `Base` as argument instead of `First`?
MOnsDaR
@monsdar what do you mean? I don't have any access to that objects.
Ockonal
Then give it access.
Alexander Rafferty
Sry, perhaps I did understand the problem wrong...
MOnsDaR
@Ockonal: Yes, using static variables to emulate object-specific data is "bad"!
Oli Charlesworth
A: 

So, you want to have two classes that don't know about eachother to communicate? While it is very possible assuming that your classes are only going to be instantiated once in you're apps lifetime, I wouldn't do it. It is bad practice.

I would definitely suggest letting the class know about the other as suggested in the above reply. If you need to do this though, you could use a global pointer to your class and assign it after it has been instantiated.

Alexander Rafferty
A: 

Instead of static you probably would check for getEnabled in your class manager:

if( obj1.getEnabled() )
{
    Second obj2;
}

The problem is that you want to get access to another class without any relation between them. So a more top-level class needs to create this relation.

MOnsDaR