C++ non-virtual method call through a base pointer: which class name is printed when the static type is A*?
#include
class A
{
public:
void CuriousTabFunction(void)
{
cout<< "Class A" << endl;
}
};
class B: public A
{
public:
void CuriousTabFunction(void)
{
cout<< "Class B" << endl;
}
};
class C : public B
{
public:
void CuriousTabFunction(void)
{
cout<< "Class C" << endl;
}
};
int main()
{
A *ptr;
B objB;
ptr = &objB;
ptr = new C();
ptr->CuriousTabFunction();
return 0;
}
-
AClass A.
-
BClass B.
-
CClass C.
-
DThe program will report compile time error.
-
ENo output.
Answer
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:
ptrhas static typeA*.- It ultimately points to an object of type
C(vianew 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.