| Lesson 3
| What is a constructor?
| Explore the use of constructor member functions.
How are C++ Constructors used?
Each class defines how objects of its type can be initialized.
Classes control object initialization by defining one or more special member functions known as constructors.
The job of a constructor is to initialize the data members of a class object. A constructor is run whenever an object of a class type is created.
In this section, we will introduce the basics of how to define a constructor. Constructors have the same name as the class. Unlike other functions, constructors have no return type. Like other functions, constructors have a (possibly empty) parameter list and a (possibly empty) function body. A class can have multiple constructors. Like any other overloaded function, the constructors must differ from each other in the number or types of their parameters.
Unlike other member functions, constructors may not be declared as const .
When we create a const object of a class type, the object does not assume its "constness" until after the constructor completes the object' s initialization.
Thus, constructors can write to const objects during their construction.
C++ Constructor Member Functions
A constructor is a member function whose name is the same as the
class name. It constructs objects of its class type.
This process involves initializing data members and, frequently, allocating free store using
new to create an object.
- can be overloaded and can take arguments
- are invoked when their associated type is used in a definition
- are invoked when call-by-value is used to pass a value to a function, or when the return value of a function must create a value of associated type