Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following classes B and D: Class B { Public; B(); B( int n); }; B::

ID: 3761506 • Letter: C

Question

Consider the following classes B and D:

Class B

{

Public;

B();

B( int n);

};

B::B()

{

cout << “B::B() ”;

}

B::B(int n)

{

cout << “B::B(“ << n << “) ”;

}

Class D : Public B

{

public:

D();

D( int n);

private:

B b;

};

D::D()

{

cout << “D::D() ”;

}

D::D(int n) : B(n)

{

b = B(-n);

cout << “D::D(“<< n <<”) ”;

}

What does the following program print? and why?

int main()

{

D d(3);

return 0;

}

Determine the answer by hand, not by compiling and running the program.

Explanation / Answer

class D extends B { private B b; public D() { System.out.println("D()"); } public D(int n) { super(n); // this gets executed first [2] and note // that the corresponding constructor from the superclass // will be called and B(3) is printed since n == 3 b = new B(-n); // this comes next [3] // when a new object is created the same constructor will // be invoked, albeit for a different object, and B(-3) // will be printed since n == 3 and -n == -3 System.out.println("D(" + n + ")"); // [3] and // finally this line prints D(3) and the original // invocation is finished and our simple program ends } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote