MC logo

Base Class Init, Virtual Functions (Answer)

  Practice Questions

The code prints


Here's what goes on:

  1. First, new Ten(10) constructs a Ten object and returns a pointer to it. The use of new runs the second class Ten constructor, which in turn calls the constructor for class Nine, which generates the output line Nine(10). The constructed object has pwr_level 10, and boron is 37. A pointer to this shiny new object is placed into n.

  2. Second, the statement Ten t; constructs another Ten object, which is called t. Constructing a derived-class object always constructs its base class part as well. Since there is no explicit base class construction, the constructor for Nine is called with no arguments, generating the line Nine(0). This object has pwr_level value 0, and boron of 2.

  3. The next group multiplies this zero by 3, then divides it by 2, and then prints the zero.

  4. The next group starts with n->up(3). Since up is not virtual, the up belonging to class Nine is used, which adds 3 to the pwr_level of the object n points to, giving 13. Then, n->down(2) is run, where down is virtual, so the 13 is (integer) divided by 2, giving 6. This value is then printed.

If the statement n->collect() were added to the main, it would produce a compiler error. This is because n is a pointer to class Nine, and collect is not defined in that class. The fact that n is pointing to an object of class Ten does not save the situation, since the compiler can only check the declared information, not what happens when the program runs and objects are created.

<<Construction and Destruction II Question