Identifying error in constructor

M

mthread

Hi,
I am writing an application in which I do quite a lot of
initialization in constructor(I am new to C++). There are
possibilities the costructor might fail. How do I identify whether a
constructor is failed or not.
 
M

Markus Moll

Hi
I am writing an application in which I do quite a lot of
initialization in constructor(I am new to C++). There are
possibilities the costructor might fail. How do I identify whether a
constructor is failed or not.

Side note: It somehow sounds like you do too much inside the constructor
(i.e. your class is responsible for too much work, but it's hard to judge
without any code).

You can throw an exception from inside the constructor to indicate failure.
This is an all or nothing approach: either the constructor terminates
successfully, in which case you have a fully functional object, or it
throws an exception, in which case you have no object at all. However, this
is generally the way to go.

Markus
 
K

Kira Yamato

Hi,
I am writing an application in which I do quite a lot of
initialization in constructor(I am new to C++). There are
possibilities the costructor might fail. How do I identify whether a
constructor is failed or not.

A::A()
try
: b(0), s("hello")
{
// body of construction
}
catch(some_exception &e)
{
// If construction of b or s fails, or the code in the body of
construction fails,
// then you get here.
// The constructor will automatically rethrow the exception.
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,966
Members
47,515
Latest member
Harvey7327

Latest Threads

Top