The first uses what is called an initialization list .
When you enter the constructor body, all class members must be constructed (so that they can be used). Therefore, if you have this:
class Foo { public: Foo() : str() // this is implicit { str = "String."; } private: std::string str; };
So str is created and then assigned. It would be better:
class Foo { public: Foo() : str("String.") { } private: std::string str; };
So str obtained directly. This does not affect your case, because pointers do not have a constructor.
It is generally considered good practice to use an initialization list over running code in the constructor. The initialization list should be used to initialize, the constructor should be used to run the code.
Also, why use a pointer to a string? If you need a string, use a string; not a pointer to a string. Most likely you really want a string.
More about initialization lists:
Initializer lists have more uses than just initializing class members. They can be used to pass arguments to the base constructors:
class Foo { public: Foo(int i) { } } class Bar : public Foo { public: Bar() : Foo(2) // pass 2 into Foo constructor. // There is no other way of doing this. { } };
Or permanent members:
class Foo { public: Foo() : pi(3.1415f) { pi = 3.1415f;
Or links:
class Foo { public: Foo(int& i) : intRef(i)
source share