Link to home
Start Free TrialLog in
Avatar of jstabik
jstabik

asked on

Ending a program from within the constructor

I'm pretty new to C++ so this may prove to be a simple question.  I have class hierarchy that is used to illustrate PC's and their components, with the base class I'm working with being the PC.  I have done some validation in the construtor using  a dynamic_cast to down cast the CPU entered by the user to a derived class.  If the cast fails then the PC can not be fitted to this kind of PC.  This all works fine but I would really like to end the program there and then from within the constructor.  At the moment all I do is cout a message saying there has been an error.  Is it possible to do something in here? I tried immediatly calling the destructor from within the constructor but that failed.

Any help at all will be a god-send.

many thanks

Janusz
ASKER CERTIFIED SOLUTION
Avatar of Karl Heinz Kremer
Karl Heinz Kremer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok ,
Call the function:
exit(0);

it will exit the program.
One more thing.
You can not call destructor within the constructor.
Avatar of Member_2_2667525
Member_2_2667525

Normally, if you want to do anything non-trivial in a constructor, it is best to change the constructor to be very simple (perhaps empty), and create an "Initialize()" class member function that you always call after constructing an instance of the class.  The most common reason to so this that I have run into is the situation you are in: you want to handle an error condition.

This would allow you to exit the program in a more graceful and structured manner (traversing up the call stack on an error condition).  Then you'd end up back in main() and you can exit() with an error code.  For example:

main()
{
      int nExitCode;
      nExitCode = MyFunc();
      if (nExitCode == 0) {
            // other function calls when MyFunc was successful
      }
      exit(nExitCode);
}

// Returns 0 on success
int MyFunc()
{
      int nReturnVal;
      MyClass x;
      nReturnVal = x.Initialize();
      if (nReturnVal != 0) {
            return nReturnVal;
      }
      // Other code executed when x initializes OK
}

It doesn't sound like you are using VC++ and MFC, but just in case, I'll mention that the above suggestion is a good way to do it so that an AfxGetMainWnd()->PostMessage(WM_CLOSE) would shut down the program in the normal Windows way (i.e., you get back into the Windows message handling loop).