RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Use Delegating Constructors to Eliminate Initialization Code Reduplication-2 : Page 2

Demonstrating the Problem
A C++ class may have multiple constructors. Often these constructors perform identical initialization steps before executing individual operations. In the worst case scenario, the identical initialization steps are copied and pasted in every constructor. Such code reduplication is a recipe for maintenance problems and bugs. Consider the following Message class:

class A;
class Message
 char *buff; 
 int msg_id;
 size_t msg_length;
 explicit Message(int);
 explicit Message(const char *);
 explicit Message(const A&);
Assume that each of the constructors first initializes the members buff, msg_id, and msg_length before performing individual operations. The code that initializes the three data members is repeated three times:

Message(int n) : buff(0), msg_id(0), msg_length(0) 
Message(const char* p) : buff(0), msg_id(0),msg_length(0) 
Message(const A& a) : buff(0), msg_id(0), msg_length(0) 
If, due to design change, you need to add more members, change the type of existing members, or even reorder members, you'll have to modify each of these constructors. Most C++ programmers avoid this code reduplication by moving the common initialization steps to a private member function that each constructor must call:

class Message
 void init() 
 explicit Message(int n) { init(); }
 explicit Message(const char * ptr) { init(); }
 explicit Message(const A& a) { init(); }
This workaround eliminates code reduplication but it creates new problems:
  • Other member functions might accidentally call init(), thus causing unexpected results.
  • An init() call inside a constructor might occur in the wrong place, or it could accidentally occur twice.
  • References and const members require a member initialization list anyway so their initialization code is still repeated in each constructor.
Let's see how delegating constructors solves this problem.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date