多態性
多態性とは、同じ名前の関数を呼び出して異なる処理を実行すること
ポリモーフィズムとも呼ばれる
オーバーロードとオーバーライドで実現することができる
オーバーロード
1つのプログラムに同じ名前で引数の数や型が違う関数を作成すること
オーバーロードを用いたプログラム
#include <iostream>
using namespace std;
class Human {
public:
void show(){
cout << "引数なしのshow関数" << endl;
}
void show(string str){
cout << "引数が" << str << "のshow関数" << endl;
}
};
int main() {
Human human;
human.show();
human.show("Taro");
return 0;
}
引数なしのshow関数
引数がTaroのshow関数
オーバーライド
基底クラスで関数を継承した派生クラスで独自に定義しなおして上書きすること
基底クラスのオーバーライドする関数にvirtual
をつける
基底クラスでオーバーライドされる関数のことを仮想関数という
オーバーライドを用いたプログラム
#include <iostream>
using namespace std;
class Human {
public:
virtual void show(){
cout << "Human class" << endl;
}
};
class Student : public Human{
public:
void show(){
cout << "Student class" << endl;
}
};
int main() {
Human human;
human.show();
Student student;
student.show();
return 0;
}
Human class
Student class
派生クラスから仮想関数を呼び出す
以下のように書くことで派生クラスから継承元の基底クラスの仮想関数を呼び出すことができます
派生クラスのオブジェクト.基底クラス::仮想関数名;
サンプルプログラム
#include <iostream>
using namespace std;
class Human {
public:
virtual void show(){
cout << "Human class" << endl;
}
};
class Student : public Human{
public:
void show(){
cout << "Student class" << endl;
}
};
int main() {
Student student;
student.Human::show();
return 0;
}
Human class