Default Constructors

A default constructor is a constructor that is used to create an object when you don’t provide explicit initialization values. That is, it’s a constructor used for declarations like this:

Stock fluffy_the_cat;  // uses the default constructor

Hey, Listing 10.3 already did that! The reason this statement works is that if you fail to provide any constructors, C++ automatically supplies a default constructor. It’s an implicit version of a default constructor, and it does nothing. For the Stock class, the default constructor would look like this:

Stock::Stock() { }

The net result is that the fluffy_the_cat object is created with its members uninitialized, just as the following creates x without providing a value for x:

int x; ...

Get C++ Primer Plus 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.