DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Two-way class communication (http://www.daniweb.com/forums/thread20560.html)

j.kelly Mar 20th, 2005 12:13 pm
Two-way class communication
 
I'm pretty new to C++ and I'm having a problem with a Uni coursework.

I have two classes A & B which need to be able to call each others functions so they each hold a pointer to the other.

I had the problem that they #included each other so I was getting an include recursion, which I solved by using forward referencing.

Now I have the problem that because I used forward referencing when I come to implement a function to use that pointer I am told that the class whose pointer I want to use is not defined.

function implementation:

void A::MyFunction()
{
    this->pointer->MyFunction();
}


headers:

class B;
class A
{
public:
    A(B* aPointer);
    ~A(void);
    void MyFunction();
private:
    B* pointer;
};

class A;
class B
{
public:
    B(A* aPointer);
    ~B(void);
    void MyFunction();
private:
    A* pointer;
};

I've given this A & B example just to simplify the problem I'm having.

Thanks,
James

j.kelly Mar 20th, 2005 12:47 pm
Re: Two-way class communication
 
Didn't realise I could just #include the other class header into the .cpp file instead of the .h file.

Problem solved.

1o0oBhP Mar 20th, 2005 9:05 pm
Re: Two-way class communication
 
Another way might be to define two classes with everything private (-constructors) and put the other classes functions as friends? the use of the static keyword could help as static fields dont require objects to be created (they can be used like 'constants' in effect)


All times are GMT -4. The time now is 3:15 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC