Connecting Tech Pros Worldwide Forums | Help | Site Map

Best way to exit a C++ Class Constructor

MrPickle's Avatar
Member
 
Join Date: Jul 2008
Posts: 100
#1: Jun 28 '09
The title says it all really?

What's the best way to exit a class constructor?

zodilla58's Avatar
Expert
 
Join Date: Dec 2006
Posts: 783
#2: Jun 29 '09

re: Best way to exit a C++ Class Constructor


Can you explain your question a bit more? When any object is created constructor is called...! What is inside your constructor class? If you can add your code snippet here!
MrPickle's Avatar
Member
 
Join Date: Jul 2008
Posts: 100
#3: Jun 29 '09

re: Best way to exit a C++ Class Constructor


Well in the constructor, say there's an error and I need to exit the constructor, normally you would use return, but because the constructor has return type I cannot use return.

eg:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. class MyClass
  4. {
  5.    public:
  6.       MyClass(int i);
  7.       int num;
  8. }
  9.  
  10. MyClass::MyClass(int i)
  11. {
  12.    if(i < 10)
  13.    {
  14.       std::cout << "Error! i is less than 10\n";
  15.       //Exit the constructor how?
  16.    }
  17.  
  18.    num = i;
  19. }
Just a quick example.
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: Jun 29 '09

re: Best way to exit a C++ Class Constructor


Of course, in your example you can silently set i to 10 and use that value but if there really is no good default value to use, throw an exception. The object won't be constructed then (a handy feature, write that down!) and it is up to the caller to fix it, i.e. either catch the exception and deal with it or die.

kind regards,

Jos
MrPickle's Avatar
Member
 
Join Date: Jul 2008
Posts: 100
#5: Jul 1 '09

re: Best way to exit a C++ Class Constructor


I see lots of different things when I look around at throw.

I see things like:
throw 1;
throw std::runtime_error("Message");

What should I be doing?
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#6: Jul 1 '09

re: Best way to exit a C++ Class Constructor


Quote:

Originally Posted by MrPickle View Post

I see lots of different things when I look around at throw.

I see things like:
throw 1;
throw std::runtime_error("Message");

What should I be doing?

Throw a specific exception; the runtime_error exception has several subclasses that may be more applicable. It also has a sibbling class: 'logic_error'; it's up to you.

kind regards,

Jos
MrPickle's Avatar
Member
 
Join Date: Jul 2008
Posts: 100
#7: Jul 1 '09

re: Best way to exit a C++ Class Constructor


Quote:

Originally Posted by JosAH View Post

Throw a specific exception; the runtime_error exception has several subclasses that may be more applicable. It also has a sibbling class: 'logic_error'; it's up to you.

kind regards,

Jos

Thank you, I will look into that.
Reply