Constructors as Member Functions

Class objects can be initialized implicitly, using a constructor. A constructor is a class member function, but its syntax is more rigid than it is for other member functions. It cannot have an arbitrary name; you should give the constructor function the same name as the class. The constructor interface cannot specify a return type, not even void. It cannot return values even if it contains a return statement.

class Cylinder {
  double radius, height;
public:
  Cylinder ()                  // same name as class, no return type
     { radius=1.0;  height=0.0; }  // no return statement
  … } ;

When client code creates an object, the default constructor is called.

Cylinder c1;                          // default constructor: no parameters

It is called a default ...

Get Core C++ A Software Engineering Approach 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.