Object-Oriented Programming

Constructors and Initialization

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Notice

The purpose of the following code examples is to demonstrate the semantics and behavior of the C++ language. They may not be complete and are not necessarily structured as they should be in actual code. Please adhere to all coding guidelines in your work.

  • Declare methods only in the header (.hpp) file
  • Define methods only in the implementation (.cpp) file
  • This also applies to constructors and destructors

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
  • The constructor initializes the allocated memory
  • The constructor does not allocate memory

Memory Allocation and the Constructor

  • For the stack:
    1. The program allocates memory from the top of the stack
    2. The constructor is called on the allocated memory in the stack
  • For the heap:
    1. The operator new allocates memory from the heap
    2. The constructor is called on the allocated memory from the heap
  • The entire memory for a class must be allocated in one contiguous chunk. The memory must be large enough for the memory requirements for all of the fields.
  • When compiling a variable declaration, the compiler must know the size of the resulting variable. The sizeof() operator shows the size of a variable or type at compile time.

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
  • The 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