15

I have as part of assignment to look into a development kit that uses the "two-phase" construction for C++ classes:

// Include Header
class someFubar{
public:
    someFubar();
    bool Construction(void);
    ~someFubar();
private:
    fooObject _fooObj;
}

In the source

// someFubar.cpp
someFubar::someFubar : _fooObj(null){ }

bool 
someFubar::Construction(void){
    bool rv = false;
    this->_fooObj = new fooObject();
    if (this->_fooObj != null) rv = true;
    return rv;
}

someFubar::~someFubar(){
    if (this->_fooObj != null) delete this->_fooObj;
}

Why would this "two-phase" be used and what benefits are there? Why not just instantiate the object initialization within the actual constructor?

4
  • 12
    This is one approach to dealing with an insane corporate coding standard that forbids exceptions. I suspect that the requirements to prefix members with underscores, use this to access members, compare pointers with null, test for null before deleting, and use (void) to indicate no parameters came from the same lunatic. Commented Jun 11, 2010 at 10:09
  • 5
    @Mike Seymour, I take exception to your suggestion that one must be a lunatic to use this to access member functions. I do it all the time as I find it more readable (and sometimes of course the use of this is necessary). I agree with the rest of your rant (what is null anyway?). Commented Jun 11, 2010 at 10:46
  • 8
    Using this where necessary, or where it enhances readability, or just using it everywhere for consistency, is fine. Prefixing members with warts so you never need to use this is also fine, although not to my taste. Doing both is lunacy. Commented Jun 11, 2010 at 10:59
  • 2
    @Mike: that was for embedded platform system, no point discussing the finer intricacies of the syntax or programming style...it's just the way it is...yours truly, a non-lunatic who has to grapple with limitations... Commented Jun 11, 2010 at 14:08

10 Answers 10

21

A document about Two Phase Construction.

The idea is that you cannot return a value from a constructor to indicate failure. The only way to indicate constructor failure is to throw an exception. This is not always desirable, not least because exception safety is a very complex topic.

So in this case the construction is split up: a constructor that does not throw, but also does not fully initialize, and a function that does the initialization and can return an indication of success or failure without (necessarily) throwing exceptions.

Sign up to request clarification or add additional context in comments.

3 Comments

The ironic thing is that more recent Symbian SDKs implement leave/trap as macros on top of try/catch.
+1 for exception safety is a very complex topic Can never be emphasized enough for C++.
Link is not found 404
7

This is useful when you have to give the user (of your class) more control on resource allocation/deallocation. For instance think of a Socket class. The user passes in the host and port parameters to the constructor and may wish to delay the actual "opening" of the sockets (i.e, allocating the low-level SOCKET object) to a later time. He may also wish to close and re-open the Socket at will. Two-phase construction (or Lazy Initialization) facilitates this. Such a Socket interface will look like:

class Socket
{
public:
    Socket (const std::string& host, int port) : host_(host), port_(port), sock_(NULL) { }
    ~Socket () { close (); }
    void open () throw (NetworkException&) 
    {
         sock_ = new_low_level_socket (host_, port_);
    }
    void close ()
    {
       if (sock_)
       {
          close_low_level_socket (sock_);
          sock_ = NULL;
       }
    }
  // private members
};

// Usage:

ing
main ()
{
    Socket sock ("www.someurl.com", 80);
    sock.open ();
    // do something with sock
    sock.close ();
    // do something else
    sock.open();
    // do something with sock
    return 0; 
    // sock is closed by destructor.
}

BTW, this idiom is not a replacement for preventing exceptions from being thrown from the constructor. If the constructor fails, throw an exception. For more information, please see this BS FAQ and the entry at C++-FAQ-Lite.

1 Comment

BS FAQ link is dead. Same seems to be true for the C++ FAQ.
6

My answer from the trenches is that two-phased construction - especially when dealing with hardware initialization - is a must. In the real world, if an object can fail to construct or control something - then a nightmare scenario is just waiting to happen.

If hardware control classes initialize the hardware in their constructors (which is attached to things that might bend, fold, spindle or mutilate humans) then the whole architecture of the application has to change to accomodate that. It changes because I can't compose my objects in the way I'd like. Maybe I want a 'master controller' that embeds all the sub-controllers. I want the freedom to construct them at any time. Objects that can fail to construct, or energize hardware when constructed throw a huge monkey wrench in the works. In those cases I have to defer creation of objects until the correct time. That means pointers to objects - which might yet be null, and which forces you to deal with null pointers to big important objects. I hate being forced to do that.

In my world view I want my constructors to be harmless, always work without fail, simply initialize all their properties (and perhaps applying some arguments to them) - And nothing else. Just prepare the object such that I can construct them, or apply references to them whenever and wherever I want one. I'll handle the 'connection' or 'initialization' of the big important pieces at a time and place of my choosing, preferably with an open(...) or init(...) method.

Comments

5

There is no good reason to do this - avoid. The original author of the code probably simply didn't know what they were doing.

5 Comments

I agree with this. Exceptions exist for a reason- throw them. Especially since Construction didn't catch, so if the constructor of fooObject threw, then it wouldn't improve exception safety. In addition, this ain't camelCase Java.
@Neil: Heh! This is an SDK from a huge company, and is a constrained kit I have to say! :D Thanks for your answer! :)
@tommie Huge does not preclude clueless - look at MFC, for example.
@Neil: True... there is a dislike for try/catch within the SDK - FYI! :D
@Neil, I think some platforms avoid exceptions for historic reasons. For example Symbian, where two-phase construction became so ingrained in the API, that they can't really get rid of it today, only hide behind a nicer toolkit (Qt), like COM and WinAPI behind .NET.
5

Why would this "two-phase" be used and what benefits are there?

This idiom is used for two reasons:

  • to separate the initialization into two different parts: the part that is always stable and will not fail (left in constructor) and the part that may fail (the separate construction function).

This idiom has been used in the past before the usage of exceptions was standardized in the language, and by library designers who didn't understand (or for some reason didn't want to use) exceptions.

You will still find it in legacy/backwards-compatible code (e.g. MFC).

  • to implement "virtual construction". Basically, you declare your Construction member function as (pure) virtual and allow specialized classes to replace it. This is almost always [1] a sign or poor design (you can and should implement your code so that you don't need this idiom).

[1] - "almost always" means here that I see no reason at all for doing it but I may be missing something :).

Comments

3

This reply is about the code in the OP, whereas a lot of the replies seem to be about some other code which is similar to the code in the OP, but where _fooObject is a pointer to a fooObject rather than a fooObject itself.

The source given is bizarre in the extreme.

If it is C++, then new cannot return 0, and should throw an exception.

If it is something not entirely unlike C++ where new returns 0 on failure (such things have been known to exist), then Construction is equivalent to:

bool someFubar::Construction(){ // no need for void in C++, it's not C
    delete _fooObj;             // nothing stops this getting called twice!
    _fooObj = new fooObject();  // no need for this->, it's not Python
    return _fooObj;             // non-zero is true 
}

someFubar::~someFubar(){
    delete fooObj;              // it's OK to delete NULL in C++. 
}

Now we have a problem - if Construction is called twice, do we construct it again and return true as above, don't construct it again and return true as it's constructed, or don't construct it again and return false as it's an error to construct something twice?

Sometimes - for example for classes which manage external resources - you may want to implement them as a state machine which you create, then allocate the resource. This is reasonable where a resource can become invalid, so you would have to check the operations you perform on it anyway. Providing a conversion from the type to bool is the pattern using in the standard library for such resources. Normally you should construct an object in one go and expect it to be valid.

4 Comments

Every C++ compiler I have ever seen has a no throw new option, and the ability to disable exceptions. Claiming that new can not return 0 is a bit hyperbolic.
I agree with the last sentence but... shrugs what can I do...the standard for that embedded platform dictates that... nowt I can do about that... but +1 from me for your answer :)
@stonemetal the code does not say _fooObj = new (nothrow) fooObject();
Agreed, and in addition the user of such an API has to remember to call someFubar::Construction(); so you've placed more burdens on the shoulders of the users of your API. IMO the name constructor is rather poor, when you consider that the it is the runtime that creates objects whereas what C++ calls constructor is actually an initializer of said object. Therefore a constructor that does not initialize its object fully, when it can does not know the reason for its existence.
2

Sometimes you have to use C++ without exceptions enabled. In that situation, the lack of a return value from a constructor makes life difficult, so you have an explicit construction function that you can test for success instead.

Comments

2

Others here have mentioned the case in which the Construction() method is virtual. One situation in which this can play a useful role is in the deserialization of an object graph (the RogueWave Tools.h++ used this technique IIRC):

  • a factory allocates the concrete subclass based on some dynamic representation of its type - perhaps by indirecting through a switch, an array, or a dictionary of some kind - whereupon...
  • ...it promptly turns around and asks the newly constructed object to deserialize its own contents - hence restoring its own state, as only it knows how to - by calling the the virtual Construction() method, perhaps passing it an input stream or whatever to read from.

Yet another use for this technique is described here: as a means of factoring common code from out of a number of overloaded constructors.

Comments

1

A reason for doing this might be that constructors don't return any values. Some persons prefer doing a Create like function that should be called after object instantiation. In case you're not using exception because they create a lot of code (especially in the embedded world) it is impossible to use just the constructor because it doesn't offer any guarantees (like I said, it cannot return any values).

Other technique that I saw was something like this:

XObject* o = new XObject();
o->IsOk();

It basically does the construction inside the constructor and holds the result of the operation inside a variable - not space efficient.

1 Comment

"not space efficient." Why not? Does o->IsOk() return the full text of Great Expectations on failure or something?
0

I certainly wouldn't be a fan of this two step construction. There's loads of other ways to get around raising an exception/error in a constructor. Firstly any C++ compiler worth it's weight should be able to throw an exception from a constructor and allow it to be caught appropriately.

Another solution would be to have an internal error code similar to the posix errno approach. And the caller could then query this error code through a call to a member of the class. IIR Windows has something like this with the GetLastError function.

3 Comments

Sorry to be blunt but -1 from me... you have to take into account of reading other comments, this is on an embedded platform, my hands are tied, cannot do anything about it despite the compiler being a iffy one....and for the sake of getting the job done... you seem to be too harsh in "any C++ compiler worth it's weight", sorry, if you're working on embedded systems then that comment is irrelevant...
@tommieb75: Sorry you feel that way, but at the time I wrote the answer nowhere in your original question or in any comment did it mention that you were dealing with an embedded platform.
that's ok... Alex B did put his finger on the comment around the same time you answered... "I think some platforms avoid exceptions for historic reasons. For example Symbian" in response to Neil's answer above. :) That was absolutely spot on. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.