Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constructors and initialization of derived classes #3

Open
Naetw opened this issue Sep 17, 2018 · 0 comments
Open

Constructors and initialization of derived classes #3

Naetw opened this issue Sep 17, 2018 · 0 comments

Comments

@Naetw
Copy link
Owner

Naetw commented Sep 17, 2018

Constructors and initialization of derived classes

專題在看 TensorFlow XLA 部分的程式碼,發現 C++ 都忘光光了,這邊紀錄一下建構 derived class 物件時跟 base class 有關的問題。

Base and Derived class:

class Base {
public:
  int m_id;
  Base(int id = 0) : m_id(id) {}
  
  int getId() const { return m_id; }
};

class Derived: public Base {
public:
  double m_cost;
  Derived(double cost = 0.0) : m_cost(cost) {}
  
  double getCost() const { return m_cost; }
};

在建構 non-derived class 物件時,建構子只需要擔心自身的成員,但如果是 derived class 的話,情況比較複雜,首先是 derived class 物件建構的流程:

  1. 分配一塊足夠空間的記憶體
  2. 呼叫適當的建構子
  3. Base class 物件會先被建構出來,如果沒有指定,會直接用預設建構子
  4. Initialization list 初始化變數
  5. 執行建構子的 body block
  6. 返還控制權給 caller

若需要設定 base class 的成員可以在 derived class 建構子的 body 中設定,但如果有成員是 const,這個方法並不能用,C++ 提供另一個方法來初始化 base class 的成員,可以在 initialization list 中指定 constructor of base class。:

class Derived: public Base {
public:
  double m_cost;
  Derived(double cost = 0.0, int id = 0) : Base(id), // call Base(int) constructor with value id
                                           m_cost(cost) {}
  // ...
};
@Naetw Naetw added the C++ label Sep 17, 2018
@Naetw Naetw added the Note label Dec 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant