継承
既存のクラスを引き継いで新しいクラスを作るための仕組み
引き継ぎ元クラスを基底クラス、引き継いで新しく定義したクラスを派生クラスという
継承の構文
class 基底クラス{
型1 メンバ変数1;
型2 メンバ変数2;
...
型a メンバ関数a
...
}
class 派生クラス : アクセス指定子 基底クラス{
型3 メンバ変数3;
...
型b メンバ関数b;
...
}
継承を用いたプログラム
#include <iostream>
using namespace std;
class Human {
public:
string name;
void show(){
cout << name << endl;
}
};
class Student : public Human {
public:
void derived(){
cout << "Studentは派生クラスです" << endl;
}
};
int main() {
Student Taro;
Taro.name = "taro";
Taro.show();
Taro.derived();
return 0;
}
taro
Studentは派生クラスです
アクセス指定子protected
基本・派生クラス内でのみアクセスできる
protected
を用いたプログラム
#include <iostream>
using namespace std;
class Human {
protected:
string name;
public:
void show(){
cout << name << endl;
}
};
class Student : public Human {
public:
void setName(string str){
name = str;
}
};
int main() {
Student Taro;
// Taro.name = "taro"; ビルドエラーが発生する
Taro.setName("taro");
Taro.show();
return 0;
}
taro
コンストラクタが呼ばれる順番
基底クラスから順にコンストラクタが呼ばれる
サンプルプログラム
#include <iostream>
using namespace std;
class Human {
public:
Human(){
cout << "Humanクラスのコンストラクタ" << endl;
}
};
class Student : public Human {
public:
Student(){
cout << "Studentクラスのコンストラクタ" << endl;
}
};
int main() {
Student taro;
return 0;
}
Humanクラスのコンストラクタ
Studentクラスのコンストラクタ