Ryan's District Boards

Computer, programming, and webmaster help , support , tips and tricks => Tutorials Zone! => Internet webmaster computer programming technology tips and tricks => C++ / C / C# ....Tutorials => Topic started by: ben2ong2 on October 06, 2006, 04:49:10 PM

Title: C++ Arrays tips and tricks : Passing arguments to arrayed object constructors
Post by: ben2ong2 on October 06, 2006, 04:49:10 PM
PROBLEM: Arrays of objects always have their empty constructors called.
There is no syntax for passing arguments to these constructors.

RESPONSE: Jim Adcock (jimad@microsoft.UUCP)

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 objects.

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; }
};

int VAL::valdefault = 0;

main()
{
   int i;

   VAL::SetDefault(234);
   VAL* AVAL = new VAL[5];

   VAL::SetDefault(432);
   VAL* AVAL2 = new VAL[5];

   return 0;
}