Object-Oriented Programming

Constructors and Initialization

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Object Construction in C++

  • Memory for the object is allocated from the stack or the heap
  • Memory from the heap is allocated using the operator new
  • Constructor initializes the allocated memory
  • Constructor does not allocate memory

Object Memory Allocation

  • Memory for the entire object is allocated first, including memory for all fields
  • For an empty class, the size is always 1 to ensure that the addresses of two different objects will be different
  • Size of an object is the sum of the size of the fields, plus the padding
  • Memory for fields is constructed first
  • Must know the fields of a class to know how much memory to allocate

Object Constructor Order

  • Constructors for all fields are called before the constructor for the object
  • Constructors are called in the order they appear in the class definition

Member Initialization Lists

  • Part of the constructor
  • Often ignored until after it is needed
  • The only way that we can control what constructor is called for the fields of the class
  • Syntax is a little strange but necessary

Non-Static Member Initialization

  • Introduced in C++11
  • Some limits to what types can be initialized and with what expressions
  • It does help that you won't forget to initialize
  • It does hurt that you cannot have initialization based on constructor parameters
  • It does hurt that it exposes implementation details
  • Use when appropriate

Good Practice

  • Don't wait for a problem to occur
  • Use the member initialization list as much as possible
  • Use non-static member initialization when appropriate