Constructors and Destructors

When you create a struct variable, the value of the member variables is not defined until you initialize them from your program. But the class allows you to declare and define a special member function, the constructor, which can initialize member variables, public or private, when an object of the class is instantiated.

The constructor is called automatically by code that the compiler generates as part of the process of instantiating the object.

The constructor has the same name as the class. It has no return type, not even void, and the most basic constructor has no arguments. For a class called aSAMSAccumulator, it would be specified in the class declaration as shown in Listing 17.5.

Listing 17.5. A Constructor ...

Get SAMS Teach Yourself C++ in 10 Minutes SECOND EDITION 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.