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

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

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

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

Class II A()

Class II default

default

  • Indicates that the compiler-provided constructor is used, even if 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
    • no user-defined destructor
    • no non-static data members that are not themselves POD
    • Does not use virtual

default vs {}

Full Application of default

delete

delete