Is there a time when a superclass's constructor is not called in C++?
This question got me in an interview. If B is A's subclass. When constructing B, is there a time when A's constructor is not called?
EDIT: I told the interviewer that I couldn't think of such case because I thought it would only make sense for a superclass to be constructed properly before constructing the s开发者_如何学Cubclass.
One possible instance is when both A and B have no user-declared constructors and an instance of B is being value-initialized.
A and B both have implicitly declared constructors which wouldn't be used in this initialization.
Similarly if A has no user-declared constructor but appears in the member initializer list of a constructor of B but with an empty initializer then A will be value-initialized when this constructor of B is used. Again, because A has not user-declared constructors the value-initialization doesn't use a constructor.
I suppose you could do something that throws an exception while generating the parameters for a non-default constructor for A in B's initialization list?
You can see below that the constructor for A is never called because an exception occurs in the parameters generation for it
#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;
}
}
Virtual Inheritance.
struct B {...};
struct D1 : virtual B {...};
struct D2 : virtual B {...};
struct Child : D1, D2 {...};
Normally the constructor B() should have been called twice, but it will be called only once.
Construction of B can't even start until A is fully constructed, so the answer is no.
If B has a second superclass that gets constructed before A, there will be a period where A's constructor has not yet been called although it is going to be.
加载中,请稍侯......
精彩评论