Defining constructors

The default constructor is used when an object is created without a value and hence the object will have to be initialized with a default value. The point declared previously could be implemented like this:

    class point     {         double x; double y;     public:         point() { x = 0; y = 0; }     };

This explicitly initializes the items to a value of zero. If you want to create an instance with the default values, you do not include parentheses.

    point p;   // default constructor called

It is important to be aware of this syntax because it is easy to write the following by mistake:

    point p();  // compiles, but is a function prototype!

This will compile because the compiler will think you are providing a function prototype as a forward ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.