Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: `new'ing an object that has a constructor Message-ID: <55908@microsoft.UUCP> Date: 18 Jul 90 15:12:19 GMT References: <5137@castle.ed.ac.uk> <1990Jul13.115822.17803@sco.COM> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Organization: Microsoft Corp., Redmond WA Lines: 48 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. Here's an example of a work-around for arrays. Use a static member function to provide a default for initializing objects. This could be generalized to providing a default function for initializing object .... extern "C" { #include "stdio.h" } class VAL { int i; static int valdefault; public: static void SetDefault(int d) { valdefault = d; } VAL() : i(valdefault) { } VAL(int ii) : i(ii) { } void SetVal(int ii) { i = ii; } int GetVal() { return i; } void Print() { printf("%d\n",i); } }; int VAL::valdefault = 0; main() { int i; VAL::SetDefault(234); VAL* AVAL = new VAL[5]; for (i=0; i<5; ++i) AVAL[i].Print(); putchar('\n'); VAL::SetDefault(432); VAL* AVAL2 = new VAL[5]; for (i=0; i<5; ++i) AVAL2[i].Print(); putchar('\n'); return 0; }