Cannot understand code

Started by
1 comment, last by NightCreature83 11 years ago

//: C14:Order.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Constructor/destructor order
#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;
} ///:~

I can't understand why that int is there,the code would be find without it.Some help?

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. (Eliminating the identifier prevents compiler warning messages.)

But still,if the int would be removed,the compiler would call those constructors by default.Why still use the int?

Just realised:

There must a user defined constructor so the member objects get initialized.That int argument is there just to remin me,in case i forget,to call the constructor for the base class too

Advertisement

Just realised:
There must a user defined constructor so the member objects get initialized.That int argument is there just to remin me,in case i forget,to call the constructor for the base class too

There is always a base constructor called. If you do not specify one the compiler will generate one using the default constructors. If a default constructor is not available you have to specify the base constructor to call.

As the author himself states the entire point of the program above is to make you do the work the compiler normally does completely automatically by artificially removing the default constructors. This is purely for illustrative purposes and not a template on how to write code.

If you removed that int you just wouldn't have to write the initialiser list is all, with the non default constructor it's an easy trick to force a compile error when forgetting to do the initialiser list.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

This topic is closed to new replies.

Advertisement