News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

C++ Arrays tips and tricks : Passing arguments to arrayed object constructors

Started by ben2ong2, October 06, 2006, 04:49:10 PM

Previous topic - Next topic

0 Members and 2 Guests are viewing this topic.

ben2ong2

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

You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login