Rus*_*ell 7 c++ inheritance constructor
这个问题让我接受采访.如果B是A的子类.在构造B时,是否有时候没有调用A的构造函数?
编辑:我告诉采访者我无法想到这种情况,因为我认为只有在构造子类之前才能正确构造超类才有意义.
一种可能的情况是当两个A和B没有用户声明的构造函数和实例B正在值初始化.
A并且B两者都隐式声明了不会在初始化中使用的构造函数.
类似地,如果A没有用户声明的构造函数但出现在构造函数的成员初始化列表中,B但是使用空的初始化程序,则在使用此构造函数时A将对其进行值初始化B.同样,因为A没有用户声明的构造函数,值初始化不使用构造函数.
我想你可以在B的初始化列表中为A的非默认构造函数生成参数时抛出异常吗?
您可以在下面看到,A的构造函数从未被调用,因为在它的参数生成中发生了异常
#include <iostream>
using namespace std;
int f()
{
throw "something"; // Never throw a string, just an example
}
class A
{
public:
A(int x) { cout << "Constructor for A called\n"; }
};
class B : public A
{
public:
B() : A(f()) {}
};
int main()
{
try
{
B b;
}
catch (const char* ex)
{
cout << "Exception: " << ex << endl;
}
}
Run Code Online (Sandbox Code Playgroud)