Question

Consider this example of code:

class Base
{
public:
    Base() {}      
};

class Derived1 : public Base
{
public:
    Derived1() : Base() {}
};

class Derived2 : public Base
{
public:
    Derived2() : Base() {}

};

Is there any to make that Derived1 has-a Derived2 and Derived2 has-a Derived1?
The best solution would be by using a third class which has those two objects. But in case high performance is needed?

An example might be a two-way client-server application.

EDIT: Consider that that's just a summary example. In the real code each of the three classes could throw an exception; I made sure that the code is exception-safe, though.

Was it helpful?

Solution

You can accomplish a "has-a" relationship with a forward declaration which basically tells "this class exists, it's just not declared yet"

#include <iostream>
using namespace std;

class Base
{
public:
    Base() {}      
};

// Forward declaration
class Derived1;

class Derived2 : public Base
{
    friend class Derived1;

public:
    Derived2() : Base() {}
private:    
    Derived1 *ptr;

};

class Derived1 : public Base
{
public:
    Derived1(Derived2& obj) : Base(), ptr(&obj) {
        obj.ptr = this;
    }
private:
    Derived2 *ptr;
};

int main() {

    Derived2 obj2;
    Derived1 obj1(obj2);



    return 0;
}

http://ideone.com/RVU8AR

This way the two classes can communicate with each other. Notice the private pointers and the initialization into the constructor. With the "friend" declaration one class is able to modify the other class's private members.

OTHER TIPS

Each class can hold a pointer:?

class Derived1
    Derived2 *p_d2;
class Derived2
    Derived1 *p_d1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top