为什么我继承的构造函数调用我的基本默认构造函数

时间:2017-10-16 13:12:32

标签: c++ inheritance constructor

也许我只是向谷歌问我的问题,但我找不到问题的答案。我的麻烦是我继承的构造函数调用我的默认基础构造函数,我真的不明白为什么。这是我的简化版。

示例:

A.cpp

#include <iostream>
#include "A.h"

using namespace std;

A::A()
{
    cout << "A" << endl;
}

B.cpp

#include <iostream>
#include "B.h"

using namespace std;

B::B()
{
    cout << "B" << endl;
}

B::B(int x)
{
    cout << "B" << x << endl;
}

Source.cpp

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main() {
    B * b = new B();
    cout << "---" << endl;
    B * b2 = new B(2);

    system("PAUSE");
    return 0;
}

输出:

A
B
---
A
B2
Press any key to continue . . .

我只是想看看B构造函数的作用。像这样:

B
---
B2
Press any key to continue . . .

1 个答案:

答案 0 :(得分:1)

因为父类可能对例如初始化子类后来依赖的成员变量(包括可能分配的内存)。

相关问题