One-Stage and Two-Stage Construction of Objects

You have a choice between two techniques for creating graphic objects, such as pens and brushes:

  • One-stage construction: Construct and initialize the object in one stage, all with the constructor.

  • Two-stage construction: Construct and initialize the object in two separate stages. The constructor creates the object and an initialization function initializes it.

Two-stage construction is always safer. In one-stage construction, the constructor could throw an exception if you provide incorrect arguments or memory allocation fails. That problem is avoided by two-stage construction, although you do have to check for failure. In either case, destroying the object is the same process.

Note

These techniques apply to creating any objects, not just graphic objects.

Example of Both Construction Techniques

The following brief example shows both methods of constructing a pen object:

// One-stage
 CPen myPen1(PS_DOT, 5, RGB(0,0,0));

// Two-stage: first construct the pen
 CPen myPen2;
 // Then initialize it 
 if(myPen2.CreatePen(PS_DOT, 5, RGB(0,0,0)))   
{
     // Use the pen
}

What do you want to know more about?

See Also

Concepts

Graphic Objects