CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Guest

    Making classes communicate with each other

    Suppose if I have 2 classes, called class A and class B and is used as follows:

    #include "A.h"
    #include "B.h"

    void main()
    {
    A objectA;
    B objectB;
    }

    Now class B need to access a variable/function of class A at run time. Simply declare "A objectA;" in class B won't work because a new objectA is created. I want class B refer to the objectA created in main function.

    Is there a solution to this? I am new to OOP and hope you can help. Thanks.


  2. #2
    Join Date
    Jun 1999
    Posts
    126

    Re: Making classes communicate with each other

    sure, pass a pointer (or reference) to objectA to objectB and store it there. Then objectB can use this pointer to access objectA.

    Timo


  3. #3
    Guest

    Re: Making classes communicate with each other

    Could you explain further by saying "pass a pointer/reference". Giving an example will be great. Thanks.

    Regards,
    John


  4. #4
    Join Date
    Jun 1999
    Posts
    25

    Re: Making classes communicate with each other

    Here your code should look like this:

    //b.h

    #include "A.h"


    class B
    {
    public:
    A *m_ptrToObjectOfClassA;
    void DoSomethingWithObjectOfClassA();

    B();
    virtual ~B();
    };




    Then in your cpp file you can do things like:

    //b.cpp

    #include "B.h"


    B:oSomethingWithObjectOfClassA()
    {
    A->VariableOfClassA++;
    }






    and your main prog is like:


    int main(int argc, char* argv[])
    {

    A ObjectA;
    B ObjectB;
    ObjectB.m_ptrToObjectOfClassA = &ObjectA;
    ObjectB.DoSomethingWithObjectOfClassA();

    }



    I think you got it..


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured