CIS 22 - Data Structure: Constructors/Destructors
The constructor for the class is invoked regardless of whether the object being created is being allocated statically or dynamically. For example, both of the statements below would automatically invoke the constructor for the class Student.
A constructor may be defined with arguments or without. A constructor that has no arguments is called the default constructor. A class may have several constructors. In the example Student class below, there are two constructors. One is the default constructor, with no arguments. The second constructor has two parameters, which are used to initialize the data members of the class Student.
How can there be more than one constructor for a class? Isn't it illegal to multiply define a function? How will the compiler know which function to invoke?
Defining several constructors for a class is an example of the C++ feature known as overloading. In general, we can define multiple versions of any C++ function, as long as the different functions have different argument lists. If the argument lists are different, then when the function is called, the compiler invokes the version that matches up to the syntax of the function call.