Many of us may not know that member variables of a class object is initialized before the body of the constructor is executed! The class type members are initialized with the default constructor i.e. constructor with no arguments. Primitive type member variable like int, float etc does not have any constructors, so they are just initialized with an undefined initial value which is often a garbage.
Anyhow, this behavior can be changed ! While defining the constructor to initialize the member variables with desired values put a colon after the constructor's last first-bracket and initialize the member variable placing a pair of first bracket after each member name; don't forget to put the value in between the first brackets. Both the class and primitive type members can be initialized in this way. Here is an example:
class A{
string m_name;
int m_id;
public:
A(int id);
A(int id, string& name);
};
/////
A::A(int id):m_id(id),m_name("No name")
{}
This is a faster way than initializing the member variables in the constructor with assignment operator. Because for the later case member variables are first initialized with their respective default garbage values than assigned with the desired values; whereas in later case they are simply initialized with the desired values !
:)
Friday, November 9, 2007
C++ Member initialization
Subscribe to:
Post Comments (Atom)
2 comments:
Nice blog... (y)
:-)
Yeah, this is a great feature of C++ constructors.
And it can be used as "resource allocation is initialization". I love this feature of C++.
Nice blog, by the way.
Post a Comment