LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++ - Two-way Communication between objects if A (obj) creates an instance of B (obj) (https://www.linuxquestions.org/questions/programming-9/c-two-way-communication-between-objects-if-a-obj-creates-an-instance-of-b-obj-873291/)

Gavin Harper 04-06-2011 04:05 AM

C++ - Two-way Communication between objects if A (obj) creates an instance of B (obj)
 
I have two classes, for argument's sake A and B.

A implements the core functionality, B is an encapsulated data structure.

If you imagine this situation

Code:

class A
{
public:
    type function();
private:
    type variable;
    B object;
};

From within B's member functions, I would like to access the public function() in class A.

This is not an inheritance issue, they are two discrete classes with radically different functionality.

Class A makes an object of B.

If someone could please offer advice about the "best practise" way to set up this communication, I would greatly appreciate it!

I would prefer advice in the form of topics or links to reading material, rather than code samples!

Thank you!

Aquarius_Girl 04-06-2011 04:17 AM

I may be barking up the wrong tree, but still, did you look up the "Friend" functionality?

Gavin Harper 04-06-2011 04:27 AM

Quote:

Originally Posted by Anisha Kaul (Post 4315514)
I may be barking up the wrong tree, but still, did you look up the "Friend" functionality?

I considered that, however, the issue is how to communicate backward?

Send a pointer of "this" from A to B?

Aquarius_Girl 04-06-2011 04:31 AM

Did you look up the C++ "Callbacks"?

JohnGraham 04-06-2011 04:55 AM

Quote:

Originally Posted by Gavin Harper (Post 4315526)
I considered that, however, the issue is how to communicate backward?

Send a pointer of "this" from A to B?

Yes, just make B accept an A* in its constructor, and then A can pass in its reference to itself when it constructs B. Just make sure that if A is ever going to disown its instance of B that you destroy B/nullify this pointer/pass it to a new A/etc. I would urge you not to consider friend classes though - for anything other than overloading certain operators, they're usually an indicator of bad design to start with.

Gavin Harper 04-06-2011 05:27 AM

Quote:

Originally Posted by JohnGraham (Post 4315559)
Yes, just make B accept an A* in its constructor, and then A can pass in its reference to itself when it constructs B. Just make sure that if A is ever going to disown its instance of B that you destroy B/nullify this pointer/pass it to a new A/etc. I would urge you not to consider friend classes though - for anything other than overloading certain operators, they're usually an indicator of bad design to start with.

Thank you!


All times are GMT -5. The time now is 05:11 PM.