Creating member objects with arguments

Nov 28, 2010 at 3:39am
I have a class, and for members it have other classes. The other classes take arguments, but the argument data is created in the constructor of the parent class.

For instance, take a simple case:

1
2
3
4
5
6
7
8
9
10
class A
{
	public:
		A(int);
}

class B
{
	A aObject(3);
}


The above would be a simple way to create an instance of A inside of B with the argument 3. For what I'm doing, I would need to create the instance of A within the constructor of B, because B does some stuff that yields the arguments that A needs.

I tried an equivalent to:

1
2
3
4
5
6
7
B::B()
{
	int arg;
	// This would be replaced with stuff to actually calculate the argument
	arg = 3;
	aObject = new A(arg);
}


But that didn't work.

I know this may seem a little redundant, but I've just come up with a bare-naked case to explain my problem simply.

Is there a way to do something that would do what my second block above suggests that I want to do? That is, is there a way to create the instance of A in the constructor of B?
Nov 28, 2010 at 8:31am
the way to call A's constructor from B's constructor is
1
2
B() : aObject(3){
}
but that's not really what you need. the best solution would probably be to white a function A::set(int) to do what constructor does. another one would be aObject = A(arg);. new allocates memory on the heap and returns a pointer to it, which is not what you need here.
Topic archived. No new replies allowed.