C++ Member initialization
Posted on | November 9, 2007 |
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 !
![]()
Comments
4 Responses to “C++ Member initialization”
Leave a Reply
November 16th, 2007 @ 1:48 am
Nice blog… (y)
November 28th, 2007 @ 11:12 am
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.
April 6th, 2008 @ 9:41 am
Sir, yes sir! I’m agreeing with you, but I don’t think everybody do. You should not be so rude, it frightens of.
April 9th, 2008 @ 2:16 am
What kind of stuff are you talking about? I didn’t get a word of it! I’ve never understood people, who spend their time on commenting stuff like that.