#include <fstream>
using namespace std;
ofstream out("order.out");
#define CLASS(ID) class ID { \
public: \
ID(int) { out << #ID " constructor\n"; } \
~ID() { out << #ID " destructor\n"; } \
};
CLASS(Base1);
CLASS(Member1);
CLASS(Member2);
CLASS(Member3);
CLASS(Member4);
class Derived1 : public Base1 {
Member1 m1;
Member2 m2;
public:
Derived1(int) : m2(1), m1(2), Base1(3) {
out << "Derived1 constructor\n";
}
~Derived1() {
out << "Derived1 destructor\n";
}
};
class Derived2 : public Derived1 {
Member3 m3;
Member4 m4;
public:
Derived2() : m3(1), Derived1(2), m4(3) {
out << "Derived2 constructor\n";
}
~Derived2() {
out << "Derived2 destructor\n";
}
};
int main() {
Derived2 d2;
}
“Note that the
constructors are not default constructors; they each have an int
argument. The argument itself has no identifier; its only reason for
existence is to force you to explicitly call the constructors in the
initializer list“
As the classes have a user-defined constructor and that user-defined
constructor is not the default constructor, there is no default
constructor available in those classes.
This makes it necessary to explicitly mention one of the available
constructors in the member initializer list of a derived class.
So much for what the code does and how it achieves it. I have no idea
why you should ever need something like that, but you never know.