CIS 22 - Data Structure: Constructors/Destructors


Explanation | Examples

Explanation

A constructor is a special function that is invoked automatically when an instance of a class is created. The constructor is declared in the same manner as a member function. The name of the constructor must be the same as the name of the class. A constructor does not have a return type (not even void).

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.

  1. Student undergrad;
  2. Student *freshman;
    freshman = new 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.

  1. Student undergrad;
    // there are no parameters here, so the default constructor will be invoked.
  2. Student grad("Joe",90);
    // this will invoke the parameterized constructor

Examples


Back to CIS 22 home page