944,181 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 4947
  • C++ RSS
Mar 20th, 2005
1

Two-way class communication

Expand Post »
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.

C++ Syntax (Toggle Plain Text)
  1. function implementation:
  2.  
  3. void A::MyFunction()
  4. {
  5. this->pointer->MyFunction();
  6. }
  7.  
  8.  
  9. headers:
  10.  
  11. class B;
  12. class A
  13. {
  14. public:
  15. A(B* aPointer);
  16. ~A(void);
  17. void MyFunction();
  18. private:
  19. B* pointer;
  20. };
  21.  
  22. class A;
  23. class B
  24. {
  25. public:
  26. B(A* aPointer);
  27. ~B(void);
  28. void MyFunction();
  29. private:
  30. A* pointer;
  31. };

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

Thanks,
James
Similar Threads
Reputation Points: 11
Solved Threads: 0
Newbie Poster
j.kelly is offline Offline
10 posts
since Mar 2005
Mar 20th, 2005
0

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.
Reputation Points: 11
Solved Threads: 0
Newbie Poster
j.kelly is offline Offline
10 posts
since Mar 2005
Mar 20th, 2005
0

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)
Reputation Points: 16
Solved Threads: 6
Posting Pro in Training
1o0oBhP is offline Offline
445 posts
since Dec 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Interactive text file
Next Thread in C++ Forum Timeline: How to get the cursor position on an image





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC