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.