GATE / CS ARCHIVE

GATE CSE 2003 / QUESTION 75

Dynamic dispatch after an upcast

Engineering Mathematics & Other Topics · Other Computing Topics · Full GATE CSE 2003 paper

GATE 2003, Q75 2 marks · MCQ
Not in GATE 2027 syllabusReport issue

Other Computing Topics

Question 75, GATE 2003: A hypothetical object-oriented language supports inheritance and dynamic binding; do not assume Java or C++ semantics beyond those facts.
class P { void f(int i) { print(i); } }
class Q subclass of P { void f(int i) { print(2*i); } }
Execute:
P x=new Q();
Q y=new Q();
P z=new Q();
x.f(1); ((P)y).f(1); z.f(1);
The cast (P)y changes the reference type to P. What is printed?
A. 1 2 1  B. 2 1 1  C. 2 1 2  D. 2 2 2
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

1. Each allocation is new Q(), so all three runtime objects have class Q even where the declared reference type is P.
2. Dynamic binding selects an override from the runtime class of the receiving object. The first call therefore invokes Q.f and prints 2×1=2.
3. Casting y to P affects its static reference type, not the object's runtime class. The second call still invokes Q.f, printing 2; z likewise points to a Q and prints 2.
4. Output 2 2 2 matches D. Static binding would be a different language rule from the one expressly stipulated.

Solution: Each allocated object is an instance of Q, including those referenced through a variable or cast of type P. With the stipulated dynamic binding, each call therefore selects Q's overriding method. For argument 1 that method prints 2, giving 2 2 2, option D. An upcast changes the reference's static type, not the runtime object or dynamically selected override.

Original paper, page 11