Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Mastering Class Member Initialization-3 : Page 3


advertisement
Test It
Use the following program to test the code:

int main() { Test t; Task task(1, t); }

The output from this program (shown in Figure 1) shows that the assignment inside Task's constructor takes place after t's construction:

 
Figure 1: Here, the assignment inside Task's constructor takes place after t's construction.



The program constructs the object t which is used as an argument for Task's constructor (line #1). Next, it constructs the sub-object name using its default constructor (line #2). Finally, Task's constructor invokes Test's assignment operator to assign n to name (line #3). The last two phases can be combined into one.

Proper Member Initialization
A real initialization of a data member uses a special syntactic construct called a member initialization list, which looks like this:

class Task { //.. public: Task(int num, const Test & n) : pid (num), name (n) {} };

Using Task's modified constructor, the same program now produces the output shown in Figure 2.

 
Figure 2: This is the output using Task's modified constructor.

Mandatory Initialization
const members, references, and sub-objects (i.e., embedded objects and base classes) whose constructors take arguments necessitate a member initialization list. For example, a class that has a data member of type std::vector can pass an argument to its constructor like this:

class Thing { private: int & ref; // reference member const int MAX; // const member vector arr; public: Thing(int& r) : ref(r), MAX(100), arr (MAX) {} };

Notice that the member MAX serves as arr's initializer. This is perfectly legal. C++ ensures that members are initialized in the order of their declaration in the class. If you change the member initialization list to:

Thing(int& r) : arr(MAX), MAX(100), ref(r) {}

The members will still be initialized in the following order: ref, MAX, and arr. However, pay attention to the members' order inside the class. Doing something like this causes unpredictable results at runtime:

class BadThing { private: int & ref; Array arr; //wrong, should appear after MAX const int MAX; };

The problem is that MAX hasnt been initialized when its value is passed to arr's constructor.



Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap