CIS 22B - Notes for Thursday, 11/5

Announcements and Reminders

  • Exercise 7 is due now
  • Assignment 7 is due next Tuesday
  • TA session tomorrow 3 pm

Recording

Exercise 7 comment

Default arguments in the set function

More Class Concepts

enums and classes

Nested classes

Constructors and Destructors

Notes from CIS27

Constructors are special class member functions that are used to create class objects.  They execute automatically when an instance of a class is created.  Constructors are used to initialize class data members.  They are also used to allocate memory for a class.  A constructor’s name is the same as the class name. 

Destructors are functions that also execute automatically when the object goes out of scope (existence). Destructors, too, have a special name.  It is the class name preceded by a ~ (tilde).  Destructors are used to release dynamically allocated memory and to perform other "cleanup" activities.

Example

class xyz
{
  private:
     .
  public:
    xyz();         // constructor prototype
    ~xyz();        // destructor prototype
     .
};

xyz::xyz()         // constructor definition
{
     .
}

xyz::~xyz()        // destructor definition
{
     .
}
     .
int main(void)
{
  xyz thing;       // the construction is called now
     .
  return 0;        // the destructor is called now
}

Notes

  • Constructors and destructors are usually placed in the public part of class definition. 

  • Both the constructor and the destructor have no return type, nor a return statement.

  • Destructors cannot have arguments.  Constructors can.  They can have several arguments, including default arguments.

  • Constructors are not usually called explicitly.  They are called automatically.  Destructors are not usually called explicitly.

  • A class may have several constructors.  If a class has multiple constructors, the argument list, including default arguments, must be unique.

  • Ctor and Dtor are abbreviations for constructor and destructor.

  • Every object must have a constructor.  If you do not provide one, the compiler will create one for you.  This constructor is a default constructor.  Default constructor also refers to a constructor without arguments.

  • Destructors are automatically called when a class object is deleted.

Examples


Video

Constructors