Constructors: No-brainer question for 35 points!

I wonder what's the best/easiest way to force the 'new' operator
to return NULL if my class constructor function doesn't like the
given parameters?

I tried using 'delete' within the  constructor, but 'new' still returns a pointer to a dead object :(



ShienShinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

clarkaCommented:
You will need to throw an exception in your constructor if the values are not what you like.  The code that is creating your object should catch the exception.
0
nietodCommented:
The new operator does two things,  It allocates memory and then it calls the constructor to intialize the memory.  Those are two indipendant steps.  If new fails to allocate memory it can return NULL (although it usually should throw an exception instead.)  Once the memory is allocated, the constructor is called to intialize it.  so you should see that A) this is new too late to prevent the allocation and B) that the constructor cannot have any affect on what new returns because the constructor is also called at onther times (i.e. when new is not used).

clarka's suggestion, to use an exception, is probably your best bet.
0
ShienShinAuthor Commented:
Will somebody kindly show some short example snippet on throwing exceptions... please... :)

My Borland documentation is rather vague and I'm a newbie to C++.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

nietodCommented:
What Borland product?  BC 5 doesn't have great support for exceptions.  BCB 4 is much better.

enum ExceptionTypes
{
   InvalidParameter,
   NoMemory,
  DiskError,
  // etc....
};

class WeekDay
{
   int Day;
public:
    WeekDay(int i) // i must be from 1 to 7.
       : Day(i)
   {
        if (i <= 0 || 7 < i)
             throw InvalidParameter;
   };
}


 int main()
{
     try
     {
            WeekDay Object(1000)l
     }
     catch (ExceptionType ErrorType)
     {
           switch (ErrorType)
           {
              case InvalidParameter:
                  cout << "Invalid parameter";
                  break;
              case NoMemoy:
                  cout << "Out of memory.";
                  break;
              case DiskError
                  cout << "There was a disk error";
                  break;

           }
     }
}

The idea is you place any code you want "protected"  code that might experience an error inside the try{...}  After this you place inside the catch{...} the code that should be called to take action if there was an error.  
0
ShienShinAuthor Commented:
Adjusted points to 45
0
ShienShinAuthor Commented:
Thanks Nietod! Just a quickie here:
If I follow your example, how would I know whether Borland C++ 5 will allocates an instance of the object?
Does exception throwing automatically
disables object instantiation, or must
I use 'delete' somewhere else later?

If not, I think I'll just add a public boolean member 'ShouldDelete' in the
class, and test the flag in main()
after using 'new' and call 'delete' in
main() if necessary... how's it?


0
nietodCommented:
>>  how would I know whether Borland C++ 5
>> will allocates an instance of the
>> object?
If control is trasnfered to the catch(){ } statement, there was an excetption.  If control follows to the next statement, there wasn't.

   try
   {
      WeekDay Object(1000);
      cout << I'm still here, no exception.";
   }
   catch (ExceptionType ErrorType)
   {
       cout << "There was an exception";
   }
               
>>Does exception throwing automatically
>> disables object instantiation,
Not really.  when an exeption is thrown, it is sort of like a return, the rest of the "scope" doesn't execute, so no objects in the scope that would be created in statements after the throw will be created, those statemetns never execute.  but unlike a simple return, the throw statement keeps returning (or at least jumping out of scopes) until it is caughts, so this make happen for any number of procedures or other scopes.

>> or must  I use 'delete' somewhere else later?
exceptions clean up locals, so in

{
    someclass X(5,3);
    throw -1;
}

X will be properly destroyed. when the exception leaves the scope.

But allocated objects are not deleted.

{
    someclass *XPtr = new someclass(5,3);
    throw -1;
}

Will not delete the object that XPtr points to.  So you must catch the exception and delete that object, then rethrow the exception.

this was clarka's suggestion, but he hasn't answered and I have been doing most of the work, so if no one (especially clarka) objects, i'm going to answer.

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ShienShinAuthor Commented:
Thanks Nietod. Will keep your advice in
mind :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.