Constructors

  • Conversion constructor <Class>(...) {}
  • Copy constructor <Class>(const <Class>& c) {}
    • Explicit conversion <Class> <new_variable>(old_variable)
    • Implicit conversion <Class> <new_ariable> = <old_variable>
  • Default copy constructor
    • Memberwise copy (copy assignment)
      • When using dynamic member, would cause memory leak if we assign one variable to another variable default-assign-problem2.cpp

  1. default
  2. explicit conversion
  3. explicit conversion
  4. implicit conversion
  5. explicit copy
  6. implicit copy
  7. explicit copy

use ()/{} is explicit, use = is implicit

Order of Constructors

  1. Parent
  2. Data members (order by their appearance in the class definition)
  3. Itself

Delegating Constructor

  • The delegated constructor must be the only item in the MIL

Member Initializer List (MIL)

  • Can be used to initalize const member variables

Safe to delete null pointer using delete

Dangling pointer point to released memory
Memory leak no pointer pointing to unreleased memory

If we still wants the default constructor, we should write <Class>() = default;

First create, last destroyed

own vs has

  • A owns B: A has pointer to B
  • A has B: B is a static data member in A

Constructor Optimization

-fno-elide-constructors

copy as value would call copy constructor
return by value would call copy constructor

tmp return object can be bind to const reference (extending its lifetime)

const quantifier cannot be applied to reference A& const, no such thing, only have such thing in pointer