Object-Oriented Programming

C++ Constructor Specifiers

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Constructor Specifiers

  • explicit
  • mutable
  • delete
  • default

Original Code

What The Compiler Does

Problem

  • Compiler can perform a single implicit conversion to get a type
  • Any single parameter constructors can be automatically called to get the type of an argument
  • Single-parameter constructor Buffer(int n) is being used

Why?

Use of explicit

Use of explicit

explicit Notes

  • The explicit specifier prevents the compiler from using that constructor for implicit conversion
  • Consider a good practice of always using explicit on single-parameter constructors until it causes a problem

Code

Code Error

Use of mutable

mutable Notes

  • Data members with mutable can change and still allow the object to be const
  • bitwise const
  • Not a single bit can change
  • logical const
  • The behavior of the object does not change
  • bitwise const implies logical const

Constructor Scenario

Class I

  • Implicit default constructor: A::A()
  • Implicit copy constructor: A::A(const A&)
  • Implicit assignment operator: A::operator=(const A&)

Class II

Class II Error

Class II

  • Implicit copy constructor: A::A(const A&)
  • Implicit assignment operator: A::operator=(const A&)
  • Implicit default constructor: A::A()

Class II A()

Class II default

default

  • Indicates that the compiler-provided constructor is used, even if it does not appear according to the constructor rules
  • Can be applied to other constructors, standard methods, and destructors

POD: Plain Old Data

  • A POD class (or struct) is a set of values without any object-oriented features (no vtable, for example)
  • All scalar types (e.g., int, double) are POD
  • POD class:
  • Has no user-defined copy assignment operator
  • Has no user-defined destructor
  • Has no non-static data members that are not themselves POD
  • Does not use virtual

default vs {}

Full Application of default

POD with default

delete

Error

delete