www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 18: Constructors and Destructors

Constructors and Destructors, Page 1

by John Kopp

Support this site at no cost to you

Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. This lesson covers constructors and destructors. Constructors and destructors are special class methods. A constructor is called whenever an object is defined or dynamically allocated using the "new" operator. The purpose of a constructor is to initialize data members and sometimes to obtain resources such as memory, or a mutex or lock on a shared resource such as a hardware device. An object's destructor is called whenever an object goes out of scope or when the "delete" operator is called on a pointer to the object. The purpose of the destructor is clean up. It is used to free memory and to release any locks or mutexes on system resources.

The definition and use of constructors and destructors is fairly simple. First, I'll outline some basic rules on constructors and destructors, and then provide the details using some simple examples.

  • A constructor is a method that has the same name as its class.
  • A destructor is a method that has as its name the class name prefixed by a tilde, ~.
  • Neither constructors nor destructors return values. They have no return type specified.
  • Constructors can have arguments.
  • Constructors can be overloaded.
  • If any constructor is written for the class, the compiler will not generate a default constructor.
  • The default constructor is a constructor with no arguments, or a constructor that provides defaults for all arguments.
  • The container classes such as vector require default constructors to be available for the classes they hold. Dynamically allocated class arrays also require a default constructor. If any constructors are defined, you should always define a default constructor as well.
  • Destructors have no arguments and thus cannot be overloaded.

Previous Page       Next Page