Sunday, May 13, 2012

using the default constructor

From page 460 of C++ Primer (4th ed)

A common mistake among programmers new to c++ is 
to declare an object initialized with the default constructor
as follows

// oops! declares a function, not an object
Sales_item myobj();

The problem is that our definition of myobj is interpreted as
a declaration of a function taking no parameters and returning 
an object of type Sales_item --- hardly we intended.  The correct
way to define an object using the default ctor is to leave off the 
trailing, empty parentheses. 

// ok: defines a class ojbect ...
Sales_item myobj;
On the other hand, this code is fine:

// ok, create an unnamed, empty sales_item and use to initialize myobj
Sales_item myobj = Sales_item();

Here we create and value-initialize a Sales_item object and to use 
it to initialize myobj.  The compiler value-initializes a Sales_item by running
its default ctor. 

No comments: