Suppose I have a class with private memebers ptr
, name
, pname
, rname
, crname
and age
. What happens if I don't initialize them myself? Here is an example:
class Example {
private:
int *ptr;
string name;
string *pname;
string &rname;
const string &crname;
int age;
public:
Example() {}
};
And then I do:
int main() {
Example ex;
}
How are the members initialized in ex? What happens with pointers? Do string
and int
get 0-intialized with default constructors string()
and int()
? What about the reference member? Also what about const references?
What else should I know about?
Does anyone know a tutorial that covers these cases? Maybe in some books? I have access in university's library to a lot of C++ books.
I'd like to learn it so I can write better (bug free) programs. Any feedback would help!
First, let me explain what a mem-initializer-list is. A mem-initializer-list is a comma-separated list of mem-initializers, where each mem-initializer is a member name followed by
(
, followed by an expression-list, followed by a)
. The expression-list is how the member is constructed. For example, inthe mem-initializer-list of the user-supplied, no-arguments constructor is
name(s_str, s_str + 8), rname(name), crname(name), age(-4)
. This mem-initializer-list means that thename
member is initialized by thestd::string
constructor that takes two input iterators, thername
member is initialized with a reference toname
, thecrname
member is initialized with a const-reference toname
, and theage
member is initialized with the value-4
.Each constructor has its own mem-initializer-list, and members can only be initialized in a prescribed order (basically the order in which the members are declared in the class). Thus, the members of
Example
can only be initialized in the order:ptr
,name
,pname
,rname
,crname
, andage
.When you do not specify a mem-initializer of a member, the C++ standard says:
Here, because
name
is a nonstatic data member of class type, it is default-initialized if no initializer forname
was specified in the mem-initializer-list. All other members ofExample
do not have class type, so they are not initialized.When the standard says that they are not initialized, this means that they can have any value. Thus, because the above code did not initialize
pname
, it could be anything.Note that you still have to follow other rules, such as the rule that references must always be initialized. It is a compiler error to not initialize references.