Base Class Init, Virtual Functions (Answer)
Here's what goes on:
new Ten(10)constructs a
Tenobject and returns a pointer to it. The use of
newruns the second class
Tenconstructor, which in turn calls the constructor for class
Nine, which generates the output line
Nine(10). The constructed object has
boronis 37. A pointer to this shiny new object is placed into
Ten t;constructs another
Tenobject, 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
Nineis called with no arguments, generating the line
Nine(0). This object has
pwr_levelvalue 0, and
upbelonging to class
Nineis used, which adds 3 to the
pwr_levelof the object
npoints to, giving 13. Then,
n->down(2)is run, where
virtual, so the 13 is (integer) divided by 2, giving 6. This value is then printed.
If the statement
were added to the
main, it would produce a compiler error.
This is because
n is a pointer to class
collect is not defined in that class.
The fact that
n is pointing to an object of
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|