inheritanceはbase classの内容を継承したderived classを定義する機能を提供します。これは、共通の項目を持つclassを親として、それぞれ新たに異なる継承した子を作成することを目的としたものです。
base classを継承する際には、継承元となるclassを指定して定義しなければなりません。
class id : base_id {}
inheritanceはこのような形式によって定義されます。
class polygon{};
class rect : polygon{};
class tri : polygon{};
この例ではpolygonがbase classであり、rect、triがderived classとなります。rectとtriはpolygonの内容を継承したclassです。
class polygon{
int width, height;
};
class rect{
int area(){
return width*height;
}
};
polygonはwidthとheightという二つのmemberが定義されています。rect、triではそのmemberが継承されています。継承されたmemberは通常のmemberと同様にアクセスすることが出来ます。
class polygon{
int w();
int h();
};
class tri{
int area(){
return w()*h()/2;
}
};
polygonはw()とh()という二つのmethodが定義されています。rect、triではそのmethodが継承されています。継承されたmethodは通常のmethodと同様にアクセスすることが出来ます。
Constructors for Base Class
base classのconstructorは、derived classのconstructor_listから呼び出すことが可能です。
class polygon{
polygon(int w, int h){
width=w;
height=h;
}
};
class rect{
rect(int w, int h) : polygon(w,h){}
};
class tri{
tri(polygon p) : polygon(p){}
};
polygon p(10,5);
rect r(p.w(),p.h());
tri t(p);
rが宣言された時、polygon(w,h)というbase classのconstructorが呼ばれます。例ではwidthが10、heightが5に初期化されます。
tが宣言された時、polygon(p)というbase classのcopy constructorが呼ばれます。よってpの値がbase classへコピーされます。
Next: Tutorial 15. Scope of Variables
Prev: Tutorial 13. Constructors