Skip to content
Official PYQ · 2003

GATE CS 2003 Q75 — Programming in C

Explain with AI

Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to  be either Java or C++, though the syntax is similar.

Class P {
    Class Q subclass of P {
        void f(int i) {
            void f(int i) {
                print(i);
                print(2*i);
            }
        }
    }
}  

Now consider the following program fragment:

P x = new Q();

Q y = new Q();

P z = new Q();

x.f(1); ((P)y).f(1); z.f(1);

Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be

Choose one option
View worked solution

Answer: D

The language is specified to use dynamic binding (runtime polymorphism). Under dynamic binding, the method to be executed is determined at runtime based on the actual object type, not the declared reference type.

  • x.f(1);: The reference x is of type P, but the actual object is of type Q. Dynamic binding invokes Q's version of f, printing 2×1=22 \times 1 = 2.
  • ((P)y).f(1);: The reference y is cast to P, but the underlying object remains of type Q. Dynamic binding still resolves to Q's version of f, printing 2×1=22 \times 1 = 2.
  • z.f(1);: The reference z is of type P, but the actual object is of type Q. This invokes Q's version of f, printing 2×1=22 \times 1 = 2.

Thus, the output produced is 2 2 2, which corresponds to Option D.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions