Skip to content

Instantly share code, notes, and snippets.

@nukopy
Last active October 26, 2020 08:26
Show Gist options
  • Select an option

  • Save nukopy/1590704757b92a2e7206e60e53bfea0f to your computer and use it in GitHub Desktop.

Select an option

Save nukopy/1590704757b92a2e7206e60e53bfea0f to your computer and use it in GitHub Desktop.
The order of constructor/destructor on base/derived class(基底クラス,派生クラスにおけるコンストラクタ,デストラクタの順序)

C++:継承とコントラクタとデストラクタ

クラスを継承した場合,コンストラクタとデストラクタの呼び出される順序には注意が必要である.コンストラクタとデストラクタの呼び出しは,以下の順番となる.

  1. 親クラスのコンストラクタ
  2. 子クラスのコンストラクタ
  3. インスタンスの主な処理
  4. 子クラスのデストラクタ
  5. 親クラスのデストラクタ

実行例

  • コンパイル & 実行
$ g++ main.cpp
$ ./a.out
  • 出力
Base::Base()
Derivative::Derivative()
void Base::x()
void Derivative::f()
Derivative::~Derivative()
Base::~Base()
#include <iostream>
using namespace std;
class Base {
public:
Base() {
cout << __PRETTY_FUNCTION__ << endl;
}
~Base() {
cout << __PRETTY_FUNCTION__ << endl;
}
void x() {
cout << __PRETTY_FUNCTION__ << endl;
}
void f() {
cout << __PRETTY_FUNCTION__ << endl;
}
};
class Derivative : public Base {
public:
Derivative() {
cout << __PRETTY_FUNCTION__ << endl;
}
~Derivative() {
cout << __PRETTY_FUNCTION__ << endl;
}
void f() {
cout << __PRETTY_FUNCTION__ << endl;
}
};
int main() {
Derivative derv;
derv.x();
derv.f();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment