tags:

views:

77

answers:

2

Hi guys,

I have a small C++ problem to which I don't know the best solution. I have two classes A and B as follows:

class A {
    int n;
    B* b;
public:
    A(int num): n(num) {
        b = new B[n];

        for (int i = 0; i < n; i++) {
            b[i].setRef(this);
        }
    }

    ~A() {
        delete [] b;
    }
};


class B {
    A* a;
public:
    B() { }

    B(A* aref) {
        a = aref;
    }

    void setRef(A* aref) {
        a = aref;
    }
};

I am creating an object of class A by passing to its constructor the number of objects of class B I want to be created. I want every object of class B to hold a pointer to the class A object that creates it. I think the best way to do this would be by passing the pointer to the class A object as a constructor argument to the class B object.

However, since I'm using the new operator, the no-args constructor for class B is called. As a result, the only solution I can see here is calling the setRef(A*) method for every object of class B after it has been constructed using the new operator.

Is there a better solution/design pattern that would be more applicable here? Would using placement new for class B be a better solution?

Thanks in advance for your help.

+1  A: 

1) Use a vector instead of memory managed memory. Use the following constructor of vector to create your B objects. This is a know limitation in native arrays:

A(std::size_t num): b_vec(num, B(this)), n(num) { }

Because you don't need deep copy constructor for B, the default one would work. Remember that there is no way to construct an array using a repeated copy of some value.

2) Use placement new, but thats just solving the wrong problem IMHO. Unless you need to call different constructors for different objects of your array.

AraK
Thank you for your help!
Abhijit
+1  A: 

Is there a reason you can't use STL? Go with a std::vector if STL is fine.

e.g.

#include <vector>

class B { ... };

class A
{
  std::vector< B > b;

  A::A( int num )
   : b( num, B( this ) )
  {
  }

  ...
};

This creates a vector of B objects, initialising each one by calling the copy constructor. This has the added bonus of removing the need to calling delete[] too.

Ben