say i have a class which the user can make an object of by passing in 2 parameters. If the parameters entered are wrong how should i handle this?

1.) should i try to create the object,and then do the checking in the constructor? if the arguments are invalid then should i cancel creation(if possible) or set the arguments to a dummy value(for example all -1 for int variables and all "zzzzz" for string variables?

2.) should i check the user arguments before the creation of the class begins? for example.

if (validArguments)
{
//create object
}
else
{
//do not create the object
}


the statement in number 2 seems reasonable to me,but what if i make a class that i want to publish for others to use. I i used solution number 2. I would have no error checking for my class! and user's would have to make their own error checking functions for it.

if i choose statement number 1(which would make my class better because it has built in error checking) i have no idea how to deal with the invalid data.

any suggestions would be greatly appreciated. -thx

That the constructor throw an exception if the parameter data is not valid. This is the simplest kind of exception handline -- in actual program you will want to expand it to throw better exception messge.

class MyClass
{
public:
   MyClass(int one, int two)
   {
      if( !one || !two)
          throw;
   }
   // finish initialization here
};

int main()
{
   try
   {
       MyClass(0,1);
   }
   catch(...)
   {
       cout << "MyClass exception caught\n";
       return 1;
   }
}

I really do not understand your situation of using the code. Do you have multiple methods with same name (over loaded constructors for the class) If so then that should take care of the problem. If this is not the case then forget about exception handling at run time, you cannot even compile the source code.

If you really want to do this then use a void* pointer and this can handle every parameter you pass to it.

Its not a good habit to place conditional completion of construtor (object)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.