ProgrammingVery hardProduct company OA
What is printed?
What is printed?
struct Base {
virtual void f() const { std::cout << "Base::f const"; }
};
struct Derived : Base {
void f() { std::cout << "Derived::f non-const"; } // note: no const here
};
int main() {
Base *p = new Derived();
p->f();
}- A. Derived::f non-const
- B. Compilation error: Derived::f does not override anything meaningfully, it's a separate non-virtual overload that hides Base::f
- C. Both print
- D. Base::f const
Correct answer: D. Base::f const
Derived::f() lacks the const qualifier, so its signature (void f()) differs from Base::f() const — it does NOT override the virtual function; it is an unrelated new (non-virtual) member that merely hides Base::f by name. Through a Base* pointer, only Base's virtual f() const is considered, and since it's virtual but Derived never actually overrode it, the vtable still points at Base::f(), printing "Base::f const".
More OOP with C++ and Java questions
- What is printed? cpp struct IWalk { virtual void move() = 0; }; struct ISwim { virtual void move() = 0; }; struct Duck : IWalk, ISwim {…
- What is printed? cpp struct Base { static void hello() { std::cout << "Base::hello"; } }; struct Derived : Base { static void hello() {…
- What is printed? cpp struct Base { virtual Base clone() { std::cout << "Base::clone "; return new Base(this); } }; struct Derived : Base {…
- What is printed? cpp class Base { public: Base() { std::cout << "Base() "; } virtual void show() { std::cout << "Base::show"; } }; class…
- What is printed? cpp class Complex { double re, im; public: Complex(double r, double i) : re(r), im(i) {} Complex operator+(const Complex&…
- What is printed? java interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) {…