tags:

views:

92

answers:

2

My question might not be too correct... What I mean is:

class MyClass
{
public:
    MyClass()
    {
    }

    virtual void Event()
    {
    }
};

class FirstClass : public MyClass
{
    string a; // I'm not even sure where to declare this...

public:
    FirstClass()
    {
    }

    virtual void Event()
    {
        a = "Hello"; // This is the variable that I wish to pass to the other class.
    }
};

class SecondClass : public MyClass
{
public:
    SecondClass()
    {
    }

    virtual void Event()
    {
        if (a == "Hello")
            cout << "This is what I wanted.";
    }
};

I hope that this makes at least a little sense...

Edit: _This changed to a.

+4  A: 

What you need to do is make SecondClass inherit from FirstClass and declare _This as protected.

class FirstClass : public MyClass
{
protected:
    string _This;

public:

and

class SecondClass : public FirstClass

What you got doesn't make sense because classes can only see members and functions from their parents (MyClass in your case). Just because two class inherit from the same parent does not mean they have any relation or know anything about each other.

Also, protected means that all classes that inherit from this class will be able to see its members, but nobody else.

Gianni
Thanks for the help!
Neffs
+1  A: 

I guess that you need something like this (for a sake of simplicity, I've omitted all the unnecessary code):

class Base{
public:
    ~Base(){}
protected:
    static int m_shared;
};

int Base::m_shared = -1;

class A : public Base{
public:

    void Event(){
        m_shared = 0;
    }

};

class B : public Base{
public:

    void Event(){
        if (m_shared == 0) {
            m_shared = 1;
        }
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    A a;
    B b;

    a.Event();
    b.Event();
    return 0;
}

To explain above, I'll explain the static data members:

Non-static members are unique per class instance and you can't share them between class instances. On the other side, static members are shared by all instances of the class.

p.s. I suggest that you read this book (especially Observer pattern). Also note that above code is not thread-safe.

sinec
Thank you for this!
Neffs