LoginSignup
1
0

More than 3 years have passed since last update.

C++の抽象クラスと子クラスのインスタンス化に関する誤解 for me

Last updated at Posted at 2020-03-18

誤解

抽象クラスはインスタンス化できないので,抽象クラスへのポインタ型変数を作ることはできない(誤).

結論

抽象クラスはインスタンス化できないが,抽象クラスへのポインタ型変数に子クラスのインスタンスのアドレスを代入することは可能.

抽象クラス

純粋仮想関数を持つクラス.
インスタンス化できない.

親クラス型の変数と子クラスのインスタンス

親クラス型の変数が使用したい関数は,継承によってその子クラスも使用できるため,親クラス型の変数に子クラスのインスタンスを代入することができる.
これらのポインタ変数も同様.
(子クラス型の変数に親クラスのインスタンスを代入することはできない.なぜならば,子クラス型の変数が使用したい関数を,親クラスが使用できるとは限らないからだ.)

具体例

ソースコード

pure.cpp
#include<iostream>


// 親クラス
class Parent {
public:
  // 純粋仮想関数
  virtual void hello() = 0;
};


// 子クラス
class Child : public Parent {
public:
  void hello() {
    std::cout << "hello" << std::endl;
  }
};


int main() {
  // 抽象クラスのインスタンス化は不可
  // Parent* parent = new Parent();

  // 親クラスへのポインタ型変数に子クラスのインスタンスのアドレスを代入することは可.
  // インスタンス化しているのは抽象クラスではなく子クラス
  Parent* parent = new Child();  
  parent->hello();  // hello
  delete parent;

  // これはエラー
  // Parent parent2 = Child();

  return 0;
}

コンパイル

$ g++ -std=c++17 -Wall --pedantic-errors -o pure.exe pure.cpp

実行結果

$ ./pure.exe
hello
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0