Foo f1 = Foo(); // (1) Ok
Foo f2 = Foo; // (2) Compiler error
Foo *p1 = new Foo(); // (3) Ok
Foo *p2 = new Foo; // (4) Ok. Why??
I was wondering why there exists two ways to initialize pointers. It looks a little inconsistent. Is there some logical reason, and if so, what? Or, maybe it's some kind of legacy? And if so, What is the origin of such notation?
It's a bit... complicated, to say the least.
When dealing with objects, both notations are equivalent. When dealing with primitive types (such as int
), (3)
will initialize (zero fill) the value, while (4)
will not (the value will be left undefined).
For automatically allocated objects, this:
Foo f1;
Declares and initializes a Foo
object using the default constructor. This:
Foo f2 = Foo();
Declares and initializes a Foo
object using the copy constructor, essentially copying the value of a temporary object (the Foo()
), which is built with the default constructor.