Course Materials

OOP - Week 2, Lecture 2: Constructors

Initializing an Object

At the end of Lecture 1, we created a Date object and never gave it any values. When we printed it, we got garbage, because the data members of a new object hold whatever was left in memory.

Date d3;                 // day, month and year are garbage

We could remember to call the setters right after creating every object, but that is easy to forget, and one forgotten call is a bug. We want an object to be valid from the moment it exists. A constructor does exactly that: it is a function that C++ runs automatically every time an object is created.

1. What Is a Constructor?

A constructor is a special member function with these rules:

  • It has the same name as the class.
  • It has no return type, not even void.
  • It runs automatically when an object is created. You never call it yourself.
  • It is usually public, so code outside the class can create objects.
class ClassName {
public:
    ClassName() {            // constructor: same name, no return type
        // give the data members their starting values
    }
};

A constructor has no return type, not even void. Writing void Date() { ... } is a compile error: β€œconstructor cannot have a return type”.

2. Types of Constructors

There are three types of constructors you will write in this lecture: a constructor with no parameters (the default constructor), a parameterized constructor, and a constructor with default parameters.

Default Constructor

A constructor with no parameters is called the default constructor. It runs when you create an object without giving any values:

class Date {
    int day, month, year;

public:
    Date() {                 // default constructor
        day = 1;
        month = 1;
        year = 2000;
    }
};

Date d;                      // runs Date(), so d holds 1/1/2000

Two rules to remember:

  • If you write no constructor, the compiler creates a default one for you. It does nothing to the data members, so they are still garbage. That is why Date d3; printed garbage in Lecture 1.
  • As soon as you write any constructor, the compiler stops creating the default one. If you only write Date(int d, int m, int y), then Date d; no longer compiles, because no constructor matches. If you still want objects without arguments, write a default constructor yourself.

Parameterized Constructor

A constructor can take parameters, so the object gets its values at creation. Pass the values in parentheses after the object’s name:

Date d1(7, 10, 2023);        // runs Date(int d, int m, int y)

Inside the constructor we reuse the setters, so the values are checked in one place:

Date(int d, int m, int y) {
    day = 1;                 // safe values first
    month = 1;
    year = 2000;
    setDay(d);               // the setters ignore invalid values
    setMonth(m);
    setYear(y);
}

Why set the safe values first? A setter ignores an invalid value and leaves the member untouched. Without the first three lines, an invalid argument would leave that member as garbage.

Constructor with Default Parameters

A parameter can have a default value, as you revised in Week 1: a value written after = in the parameter list. If the caller leaves that argument out, the default value is used. A constructor with default parameters can be called with no arguments, with some, or with all of them:

class Date {
    int day, month, year;

public:
    Date(int d = 1, int m = 1, int y = 2000) {
        day = 1;
        month = 1;
        year = 2000;
        setDay(d);
        setMonth(m);
        setYear(y);
    }
    // setters and getters as before
};

Date a;                      // 1/1/2000    no arguments, all defaults used
Date b(7);                   // 7/1/2000    only the day is given
Date c(7, 10);               // 7/10/2000   day and month are given
Date e(7, 10, 2023);         // 7/10/2023   everything is given

This one constructor does the job of both the default constructor and the parameterized constructor. It counts as a default constructor, because it can be called with no arguments.

  • Default values are filled in from the right. Once a parameter has a default value, every parameter after it needs one too. Date(int d = 1, int m, int y = 2000) does not compile.
  • Arguments are matched from the left. You cannot give only the month and skip the day.

Do not write both Date() and Date(int d = 1, int m = 1, int y = 2000) in the same class. Date x; could call either one, so the compiler reports that the call is ambiguous. Keep one of them.

3. Constructor Overloading

A class can have several constructors, as long as their parameter lists are different. This is the function overloading you revised in Week 1. C++ looks at the arguments you pass and runs the matching constructor:

Date d3;                     // no arguments: default constructor
Date d1(7, 10, 2023);        // three ints: parameterized constructor

Do not write Date d(); with empty parentheses. C++ reads it as the declaration of a function named d that returns a Date, not as an object. To use the default constructor, write Date d;.

4. Member Initializer List

There is a second way to give the data members their values: a member initializer list. It goes between the closing parenthesis of the constructor and the opening brace, after a colon:

Date(int d, int m, int y) : day(d), month(m), year(y) {
    // the body can be empty
}

Each member is followed by its starting value in parentheses, and the members are separated by commas. The list runs before the body, so the members are created with their values instead of being created first and assigned later.

An initializer list can be combined with default values in the same constructor. The arguments (or the default values, when an argument is left out) go into the parameters, and the list copies the parameters into the members:

Date(int d = 1, int m = 1, int y = 2000) : day(d), month(m), year(y) { }

Date a;                      // 1/1/2000   all the default values are used
Date b(7, 10);               // 7/10/2000  the year uses its default value
Date c(7, 10, 2023);         // 7/10/2023  every argument is given
  • The initializer list does not check the values. For validation, use the setters in the body, as in the example above.
  • Members are initialized in the order they are declared in the class, not the order you write them in the list. This can cause a bug:

    class Example {
        int a, b;                        // a is declared first, so a is initialized first
    
    public:
        Example(int x) : b(x), a(b) { }  // a(b) runs before b(x): a copies a b that has no value yet
    };
    

    The compiler warns about this, with a message like β€œfield b will be initialized after field a” (the exact words depend on your compiler). Write the list in the same order as the declarations.

  • The initializer list becomes necessary for const members and for members that are themselves objects. We will meet both in Week 4.

5. Putting It Together

This is the program from Lecture 1, now with two constructors. The green lines are what changed since Lecture 1. d1, d2 and d4 use the parameterized constructor, and d3 uses the default constructor.

Date class with constructorscode/oop/week-02/date-2
added since Lecture 1 has a note
#include <iostream>
using namespace std;

class Date {
private:
    int day, month, year;

public:
    Date() {                        // default constructor
        day = 1;
        month = 1;
        year = 2000;
    }
    Date(int d, int m, int y) {     // parameterized constructor
        day = 1;                    // safe values first, in case an argument is invalid
        month = 1;
        year = 2000;
        setDay(d);                  // the setters check the values
        setMonth(m);
        setYear(y);
    }

    void setDay(int d) {
        if (d < 1 || d > 31)        // validation
            return;
        day = d;
    }
    void setMonth(int m) {
        if (m < 1 || m > 12)        // validation
            return;
        month = m;
    }
    void setYear(int y) {
        if (y < 1)                  // validation
            return;
        year = y;
    }

    int getDay() {
        return day;
    }
    int getMonth() {
        return month;
    }
    int getYear() {
        return year;
    }
};

int main() {
    Date d1(7, 10, 2023);
    Date d2(19, 9, 2026);
    Date d3;                        // default constructor
    Date d4(31, 13, 2020);          // month 13 is invalid

    cout << d1.getDay() << "/" << d1.getMonth() << "/" << d1.getYear() << endl;
    cout << d2.getDay() << "/" << d2.getMonth() << "/" << d2.getYear() << endl;
    cout << d3.getDay() << "/" << d3.getMonth() << "/" << d3.getYear() << endl;
    cout << d4.getDay() << "/" << d4.getMonth() << "/" << d4.getYear() << endl;

    return 0;
}
Terminal
g++ main.cpp -o app
./app
Tip: click a line of output to jump to the code that printed it.Output hidden. Try it yourself first.