Path: utzoo!attcan!ncrcan!scocan!jfischer From: jfischer@sco.COM (Jonathan Fischer) Newsgroups: comp.lang.c++ Subject: Re: `new'ing an object that has a constructor Message-ID: <1990Jul13.115822.17803@sco.COM> Date: 13 Jul 90 15:58:22 GMT References: <5137@castle.ed.ac.uk> Reply-To: jfischer@sco.COM (Jonathan Fischer) Organization: SCO Canada, Inc. (formerly HCR Corporation) Lines: 38 In article <5137@castle.ed.ac.uk> ecsv38@castle.ed.ac.uk (S Manoharan) writes: >Well, the subject line says it all. How do I `new' an object >that's got a constructor? I am interested in `new'ing an array >of such objects. Unfortunately, you can't 'new' an array of objects unless the class has a default constructor. This means that you can't pass an initializer to a new stmt for an array. The default constructor is called for each element of the array (in ascending order). So, your "A *p2 = new A[10];" would work if you added a default constructor to A. Of course, you'd then have to set up each element, and to do that you'd need some sort of A::SetValues() member function. Not too nice. To initialize the elements in the declaration, rather than > A *p2 = new A(3)[10]; you can try: A p2[10] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; Of course this isn't dynamic. If you want a dynamically-allocated array of A and you want to pass a value to the constructor, do the following: A **p = new A* [ ArraySize ]; for ( int i = 0; i < ArraySize; ++i ) { p[i] = new A( InitialValue ); } Here each p[i] is a pointer to A, where each p2[i] above is an actual object A. -- Jonathan Fischer SCO Canada, Inc. Toronto, Ontario, Canada Usenet's first law of Flamodynamics: For every opinion, there is an equal and opposite counter-opinion.