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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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; public: 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() { buff=0; msg_id=0; msg_length=0; } public: 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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



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