[comp.lang.c++] calling

inst182@tuvie (Inst.f.Techn.Informatik) (02/08/90)

I have a problem: I want to dynamically create an array of
a class as a member of another class. Now I cannot use the 
new operator, because the constructors of this class all
have at least one argument. Thus, I'd like to allocate the 
memory with malloc and call the constructor explicitly 
for each element. Can I do anything to make 
this legal:

class foo {

	/* something */
public:

	foo(int);
	~foo();
}

class bar { 
	/* something else */

public:

	bar(int,int);
	~bar();

}

bar::bar(int x, int y){

	foo	*help, *h2;

	help = (foo *) malloc (sizeof(foo)*x);

	for (h2 = help ; h2 < help +x ; h2++){
		h2->foo(y);
	}
}


One way would be to have a function that really dowes the initialization
and call this from the constructor. This function, I could also call
from the bar::bar() routine, but if I for example do not have the source
of foo, that will not be an alternative. *ANY* hints ?


				Thanx in advance,
					mike

       ____  ____
      /   / / / /   Michael K. Gschwind             mike@vlsivie.at
     /   / / / /    Institute for VLSI-Design       mike@vlsivie.uucp
     ---/           Technical University, Vienna 
       / 
   ___/ 

horstman@sjsumcs.sjsu.edu (Cay Horstmann) (02/12/90)

In article <1088@tuvie> inst182@tuvie (Inst.f.Techn.Informatik) writes:
>
>I have a problem: I want to dynamically create an array of
>a class as a member of another class. Now I cannot use the 
>new operator, because the constructors of this class all
>have at least one argument. Thus, I'd like to allocate the 
>memory with malloc and call the constructor explicitly 
>for each element. Can I do anything to make 
>this legal:
>
>
In C++ 2.0, you can launch a constructor on a pre-allocated area, but
it is not a pretty sight. You say "new (p) X( arg )" to run X::X( arg ) on
the area of memory starting at p. 

See Lippmann for the details.

I suppose you are doing this because you don't own X--otherwise I
think it would make far more sense to add a X::X() and an explicit
function to do the initialization, say X::init( arg ). 

Cay