Ways to Provide a Default Constructor for a Class

Any constructor that takes no arguments is called a default constructor. A class can get a default constructor in one of several ways:

1. The compiler implicitly creates a default constructor in every class that does not have any user-defined constructors. The default constructor does not initialize the class’s data members, but does call the default constructor for each data member that’s an object of another class. An uninitialized variable contains an undefined (“garbage”) value.

2. You explicitly define a constructor that takes no arguments. Such a default constructor will call the default constructor for each data member that’s an object of another class and will perform additional initialization specified by you.

3. If you define any constructors with arguments, C++ will not implicitly create a default constructor for that class. We’ll show later that C++11 allows you to force the compiler to create the default constructor even if you’ve defined non-default constructors.

Image

For each version of class GradeBook in Fig. 3.1, Fig. 3.3 and Fig. 3.5 the compiler implicitly defined a default constructor.


Image Error-Prevention Tip 3.2

Unless no initialization of your class’s data members is necessary (almost never), provide constructors to ensure that your class’s data members are initialized with meaningful values when each new object of your class is created.



Image Software Engineering Observation 3.2

Data members can be initialized in a constructor, or their values may be set later after the object is created. However, it’s a good software engineering practice to ensure that an object is fully initialized before the client code invokes the object’s member functions. You should not rely on the client code to ensure that an object gets initialized properly.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175