Browse DevX
Sign up for e-mail newsletters from DevX


Mastering Class Member Initialization-2 : Page 2




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

Distinguishing Between Assignment and Initialization
Some programmers believe that the proper place for initializing data members is inside a constructor. For example:

class Task { private: int pid; string name; public: Task(int num, const string & n) { pid=num; name=n; } };

This is wrong. The two statements in the constructor assign, rather than initialize, the members pid and name. When dealing with objects, the performance overhead can be noticeable. The object is first constructed and only then is it assigned. To see the difference, replace the type of the member name. Instead of a string, it will be an object of the following class. By the way, notice how the static data member is initialized:

class Test { public: Test() { ctor_count++; cout<<"ctor "<<ctor_count<<endl; } Test(const Test & r) { ctor_count++; cout<<"copy ctor "<<ctor_count<<endl; } Test & operator= (const Test& r) { ctor_count++; cout<<"assignment op "<<ctor_count<<endl; return *this; } private: static int ctor_count; //only a declaration }; int Test::ctor_count=0; // definition + initialization

ctor_count is a static member thats incremented every time its constructor, copy-constructor, or assignment operator is called. This way, you can track the phases of its construction. Notice that only the definition of a static data member may initialize it (I will discuss the initialization of const static members shortly). Class Task now looks as follows:

class Task { private: int pid; Test name; // type changed from string to Test public: Task (int num, const Test & n) {pid=num; name=n;} };

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