C++ non-virtual method call through a base pointer: which class name is printed when the static type is A*?\n\n#include<iostream.h>\nclass A\n{\n public:\n void CuriousTabFunction(void)\n {\n cout<< "Class A" << endl;\n }\n};\nclass B: public A\n{\n public:\n void CuriousTabFunction(void)\n {\n cout<< "Class B" << endl;\n }\n};\nclass C : public B\n{\n public:\n void CuriousTabFunction(void)\n {\n cout<< "Class C" << endl;\n }\n};\nint main()\n{\n A *ptr;\n B objB;\n ptr = &objB;\n ptr = new C();\n ptr->CuriousTabFunction();\n return 0;\n}

Difficulty: Easy

Correct Answer: Class A.

Explanation:


Introduction / Context:
This program tests dynamic dispatch vs. static binding. Member functions are not declared virtual, so calls through a base pointer use static type information, not the dynamic type of the object.


Given Data / Assumptions:

  • ptr has static type A*.
  • It ultimately points to an object of type C (via new C()).
  • Each class defines a method with the same name and signature, but none are virtual.


Concept / Approach:
Without virtual, the call is statically bound to A::CuriousTabFunction because the expression type is A*. Dynamic dispatch would require virtual on the base declaration to select the most-derived override at runtime.


Step-by-Step Solution:
1) ptr becomes an A* pointing at a C object. 2) ptr->CuriousTabFunction() is compiled to call A::CuriousTabFunction due to static binding. 3) The output is “Class A”.


Verification / Alternative check:
Mark CuriousTabFunction as virtual in A and rerun; the output becomes “Class C”.


Why Other Options Are Wrong:
“Class B” or “Class C” would require virtual dispatch. There is no compile-time error since method lookup succeeds and signatures match.


Common Pitfalls:
Assuming polymorphism without declaring methods virtual; forgetting that overriding without virtual still hides but does not polymorphically override.


Final Answer:
Class A.

More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion