Friday 27 October 2017

What does a colon following a C++ constructor name do?

It is an initialization list.



By the time you get in the body of the
constructor, all fields have already been constructed; if they have default
constructors, those were already called. Now, if you assign a value to them in the body
of the constructor, you are calling the copy assignment operator, which may mean
releasing and reacquiring resources (e.g. memory) if the object has any.



So in the case of primitive types like int,
there's no advantage compared to assigning them in the body of the constructor. In the
case of objects that have a constructor, it is a performance optimization because it
avoids going through two object initializations instead of
one.



An initialization list is necessary if one
of the fields is a reference because a reference can never be null, not even in the
brief time between object construction and the body of the constructor. The following
raises error C2758: 'MyClass::member_' : must be initialized in constructor base/member
initializer list



class MyClass
{

public :
MyClass(std::string& arg) {

member_ = arg;
}
std::string&
member_;
};


The
only correct way
is:




class MyClass
{
public :
MyClass(std::string& arg)
: member_(arg)

{
}
std::string&
member_;
};

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...