繼承的建構式與解構式

生成衍生類別的物件時若不指定參數,無參數的預設建構子會被執行,而基礎類別的無參數預設建構子也會被執行。生成衍生物件實例時可指定參數,並指定基底類別中的某個有參數的建構子,以下為簡單的示範。

class Point2D { 
private:
    int m_x;
    int m_y; 
public: 
    Point2D();
    Point2D(int x, int y);
}; 

class Point3D : public Point2D { 
private:
    int m_z; 
public: 
    Point3D();
    Point3D(int x, int y, int z);
};

Point2D::Point2D(){
    m_x = 0;
    m_y = 0;
}
Point2D::Point2D(int x, int y){
    m_x = x;
    m_y = y;
}
Point3D::Point3D(){
    m_z = 0;
}
Point3D::Point3D(int x, int y, int z){
    Point2D(x, y);
    m_z = z;
}

如果生成衍生類別物件,順序會從基底類別的建構式開始執行,再到衍生類別的建構式,而在物件被消滅時,解構函式的執行順序則正好相反,從衍生類別的解構式開始執行,再來才是基礎類別的解構式,下面程式碼可以看出建構式和解構式的順序。

#include <iostream> 
using namespace std; 

class Father { 
public: 
    Father() { 
        cout << "父類別建構函式" << endl; 
    } 
    ~Father() { 
        cout << "父類別解構函式" << endl; 
    } 
}; 

class Son : public Father { 
public: 
    Son() { 
        cout << "子類別建構函式" << endl; 
    } 
    ~Son() { 
        cout << "子類別解構函式" << endl; 
    } 
}; 

int main() { 
    Son son; 
    return 0;
}