(原創) derived-class要怎麼呼叫base-class的constructor? (C/C++)
有時我們在derived-class的constructor提供的參數,事實上是base-class的資料,或者base-class根本就是ABC(abstract base class),這時我們就得在derived-class的constructor去呼叫base-class的constructor。
1/*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor.cpp
5Compiler : Visual C++ 8.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to call base class constructor
7Release : 02/16/2007 1.0
8*/
9#include <iostream>
10#include <string>
11
12using namespace std;
13
14class Student {
15public:
16 string name;
17public:
18 Student() {}
19
20 Student(const char *name) {
21 this->name = string(name);
22 }
23};
24
25class Bachelor : public Student {
26public:
27 string lab;
28
29public:
30 Bachelor() {}
31
32 Bachelor(const char *name, const char *lab) : Student(name) {
33 this->lab = string(lab);
34 }
35};
36
37int main() {
38 Bachelor bachelor("John","PECLab");
39 cout << bachelor.name << endl;
40 cout << bachelor.lab << endl;
41}
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : Constructor_CallBaseConstructor.cpp
5Compiler : Visual C++ 8.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to call base class constructor
7Release : 02/16/2007 1.0
8*/
9#include <iostream>
10#include <string>
11
12using namespace std;
13
14class Student {
15public:
16 string name;
17public:
18 Student() {}
19
20 Student(const char *name) {
21 this->name = string(name);
22 }
23};
24
25class Bachelor : public Student {
26public:
27 string lab;
28
29public:
30 Bachelor() {}
31
32 Bachelor(const char *name, const char *lab) : Student(name) {
33 this->lab = string(lab);
34 }
35};
36
37int main() {
38 Bachelor bachelor("John","PECLab");
39 cout << bachelor.name << endl;
40 cout << bachelor.lab << endl;
41}
執行結果
John
PECLab
PECLab
32行的constructor提供了兩個參數,name為base-class的資料,而lab為derived-class的資料,所以勢必呼叫base-class的constructor才行,C++的方式是在constructor initializer list中呼叫base-class的constructor名稱,並帶入參數,這樣就可以執行base-class的constructor了。
C#是在constructor initializer list使用base這個keyword,而Java是在body中使用super這個keyword。
See Also
(原創) derived-class要怎麼呼叫base-class的constructor? (.NET) (C#)
(原創) derived-class要怎麼呼叫base-class的constructor? (Java)
Reference
C++ Primer 4th section 15.4.2 p.582