Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
171 字
1 分钟
Constructors and Destructors

Features of a Constructor#

A constructor is a special member function that is automatically called when an object is created.

Main Features#

  • Has the same name as the class
  • No return type (not even void)
  • Called automatically when an object is instantiated
  • Used to initialize data members
  • Can be overloaded (default, parameterized, copy, move)
  • Can use an initializer list
  • Can have default arguments
  • Usually declared public
  • Cannot be inherited, but base-class constructors are called during object creation

Features of a Destructor#

A destructor is a special member function that is automatically called when an object is destroyed.

Main Features#

  • Name is the class name prefixed with ~
  • No return type and no parameters
  • Called automatically when an object goes out of scope or is deleted
  • Used to release resources (memory, files, locks)
  • Only one destructor per class (cannot be overloaded)
  • Can be virtual (important for polymorphism)
  • Called in reverse order of construction
  • Usually declared public

Constructor vs Destructor (Quick Comparison)#

FeatureConstructorDestructor
PurposeInitialize objectClean up resources
When calledObject creationObject destruction
ParametersAllowedNot allowed
OverloadingAllowedNot allowed
InheritanceNot inheritedNot inherited
VirtualNo (usually)Yes (often needed)

One-Line Exam Summary#

  • A constructor initializes an object automatically when it is created.
  • A destructor cleans up resources automatically when the object is destroyed.
Constructors and Destructors
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/constructors-and-destructors/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00