MC logo

Construction and Destruction II (Answer)

  Practice Questions

The code prints:

Zero
a = 42
cloned 0
fred: 0
bye 0
barney: 126
bye 126
bye 0

Or, more verbosely:
ZeroGenerated by the first constructor, which is called by the declaration Azure x;
a = 42Generated by the second constructor, which is called by the declaration Azure y(42);
cloned 0Generated by the copy constructor (the third one), which is called by the copy needed to pass the object x to the parameter a of fred.
fred: 0Output by fred.
bye 0Generated by the destructor when parameter a of fred passes away at the end of fred.
Note: Sending y to barney does not generate output from the copy constructor because it is passed by reference. Therefore, no copy is made. Likewise, there is no destructor called at the end of barney to destroy the copy.
barney: 126Output from barney.
bye 126
bye 0
These last two lines are from the destruction of x and y at the end of main. The system is free to destroy the objects in any order, hence the order of these two lines is system-dependent.


<<Construction and Destruction I Question Base Class Init, Virtual Functions>>